1

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. E.g. 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.

user31782
  • 7,087
  • 14
  • 68
  • 143

2 Answers2

5

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>
Jed Fox
  • 2,979
  • 5
  • 28
  • 38
Rayon
  • 36,219
  • 4
  • 49
  • 76
2

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>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • I've edited the question. I am not asking how to select the child. I am asking why can't I select it as `document.getElementById("my_div").span`? – user31782 Apr 25 '16 at 10:35
  • Yes it returns object but there is no span property inside https://jsfiddle.net/Lg0wyt9u/609/ here is a list of all properties https://jsfiddle.net/Lg0wyt9u/610/ – Nenad Vracar Apr 25 '16 at 10:43