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>
.main
to main
in getElementsByClassName
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>
document.getElementsByClassName
returns a collection of HTML elements, not a single element document.getElementsByClassName
you should pass main
, not .main
main
is probably not what you expectquerySelector
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.