简体   繁体   中英

Why console giving me result undefined

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>

  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>

  • 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM