Mahmed1;1292459 wrote:Or is this correct
Code:
<p id="test">
This
<span id="span">is</span>
a test.
</p>
This - is the first child of p tag
Span tag - is the second child and next sibling to (This)
A test - is the 3rd child
The word (IS) is the first and only child to the Span tag
So this code refers to the word IS?
This - is a text node so it is correct that it is a first child of a "p" tag.
span - is not a second child of "p" tag (although it is but I would say that practically it isn't when you access it this way). It's a nextSibling because it is on the same level as text node.
a test - is a nextSibling
Oops i meant this code refers to IS
var p = document.getElementById('test);
var s = p.firstChild.nextSibling.firstChild
That's correct. You initialize your p variable to hold "p" (id=test) element. Then you navigate down to the "is" text node by getting to the first child of that "p" element which is a text node. Then you get it's next sibling which is a "span" tag and at the end you get span's first child which is another text node "is" text.
If you have one element inside another then above element is it's parent. For example:
<div><p></p></div>
so "div" is a parent element and "p" is a child element.
If elements are on the same levele then they are siblings. Consider the following example:
<div><p></p><h1></h1></div>
now the "div" element is a parent element and his children are "p" and "h1" tags. P tag is it's first child but "h1" tag is nextSibling because it's on the same levele as is "p" tag.
So this is just a one way how you can navigate the DOM tree. There are also other ways to do the same thing like for example you could use Node object's "element.childNodes" property to return a node list of child nodes for an element.
Depending on technique you use you'll have "second child, third child...". Obviously if you use Core Node object's properties such as firstChild, nextSibling... you won't have (practically) any second child, third child... because you'll always have to grab some element's first child and then if there are any other children you'll have to use nextSibling, previousSibling...properties to traverse the DOM.
If you decide to use "element.childNodes" to retrieve a list of child elements then you'll have "second child, third child..." and you can use expression like:
var child = element.childNode[n] // where n respresents child element you want to access