Suppose I have a simple html code sonsisiting a parent div
and child span
element as:
<div id="my_div"><span> Nothin' but the G thang </span></div>
It is said that every element in html DOM is an object. So we can select child objects as parent.child
. Eg window.document
, window.document.body
, window.document.head
etc then my question is why does document.getElementById("my_div").span
return undefined?
Similarly window.document.body
works but I can't go one level down after that with window.document.body.div
.
With .
( dot-notation
), you are trying to access the span
property of the object
( Node/Element
) returned by document.getElementById
. As there is no span
property associated with returned object, document.getElementById("my_div").span
will be undefined
Use document.querySelector
, Returns the first element within the document (using depth-first pre-order traversal of the document's nodes|by first element in document markup and iterating through sequential nodes by order of amount of child nodes) that matches the specified group of selectors
console.log(document.querySelector('#my_div span'));
<div id="my_div"><span> Nothin' but the G thang </span> </div>
Or Node.chilren
, read-only property that returns a live HTMLCollection of the child elements of Node.
console.log(document.getElementById('my_div').children[0]);
<div id="my_div"><span> Nothin' but the G thang </span> </div>
You can select span like this
var span = document.getElementById("my_div").querySelector('span'); console.log(span);
<div id="my_div"><span> Nothin' but the G thang </span> </div>
Or in your case you can also use firstChild
var span = document.getElementById("my_div").firstChild; console.log(span);
<div id="my_div"><span>Nothin' but the G thang </span></div>
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.