Home > Software design >  Why console giving me result undefined
Why console giving me result undefined

Time:10-30

I Don't khow why my console is telling me that the result is undefined.I am learning DOM and found the problem on my first code which i don't understand

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>

        let head = document.getElementsByClassName(".main");

        console.log(head.textContent);

        let tail = document.getElementsByTagName("p");

        console.log(tail.textContent);

    </script>
</head>

<body>

    <div class="main">
        <p>hello</p>
    </div>

</body>

</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

  1. The elements doesn´t exist when the script runs in head. Move the script to after the elements
  2. Change from .main to main in getElementsByClassName
  3. getElementsByClassName returns a list so add [0] to getElementsByClassName("main") to get the first element

<div class="main">
    <p>hello</p>
</div>

<script>
    let head = document.getElementsByClassName("main")[0];
    console.log(head.textContent);

    let tail = document.getElementsByTagName("p")[0];
    console.log(tail.textContent);
</script>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

  • Move your script to the body
  • document.getElementsByClassName returns a collection of HTML elements, not a single element
  • with document.getElementsByClassName you should pass main, not .main
  • the textContent of the div with class main is probably not what you expect
  • to get an single element by its class name or its tag name, you can also use querySelector which is more simple (but slower) Here is a working version :
<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>

    <body>
        <div class="main">
            <p>hello</p>
        </div>
  
        <script>
            let head = document.querySelector(".main");
            console.log(head.textContent);
            let tail = document.querySelector("p");
            console.log(tail.textContent);
        </script>
    </body>

</html>
  • Related