- 1
How do i change the content of the first paragraph by using the "firstChild " property? Also plz explain the mistake i've made
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> <div id="hello"> <p>this</p> <p>this</p> <p>this</p> </div> <script> document.getElementById("hello").firstChild.innerHTML="does this"; </script> </body> </html>
2 ответов
+ 5
This is tricky: depending on browsers, the DOM tree isn't always the same: some are considerating empty nodes, while others don't... #hello <div> could be considerated as with a first 'text' empty node child (the spaces and new line between opening <div> and opening <p>), so you've not the 'firstChild' expected ^^
You can workaround by having the first child tag without any space after the parent opening tag (but it's not very safe) or searching the first child with the right type... but simplest way is to use powerful of querySelector() and querySelectorAll() method (which use css selectors syntax to get element(s) reference):
document.querySelector('#hello>p:first-child').innerHTML = 'does this';
0
thanks for answering