Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How ChildNode Works

<html>
  <head>

    <title></title>
    <script type="text/javascript"><!--
function test2() {
  var val2 = document.getElementById("ex2").childNodes[1].childNodes[0].nodeValue;
  alert(val2);
}
--></script>

  </head>
  <body>
        <div id="ex2">Web courses - <span>http://coursesweb.net</span> - lessons, tutorials</div>
<a href="#" onclick="test2()" title="childNodes example">Test 2</a>
  </body>
</html>

Above alerts http://coursesweb.net.

But if i add <p>Some text</p> and than i try to add childNodes[2] its not working.

Can some one please explain me this code and ChildNode Concept too.

like image 223
Swati kothari Avatar asked Nov 18 '25 11:11

Swati kothari


2 Answers

Tracing the original query document.getElementById("ex2").childNodes[1].childNodes[0].nodeValue; we find:

document.getElementById("ex2") => <div id="ex2">Web courses -<span>http://coursesweb.net</span> - lessons, tutorials</div>

Because the textNode "Web courses" is the first node

.childNodes[1] => <span>http://coursesweb.net</span>

.childNodes[0] => textNode "http://coursesweb.net"

.nodeValue => "http://coursesweb.net"

If you want to add <p>Some text</p> make your original ex2 string:

<div id="ex2">Web courses - <span>http://coursesweb.net</span><p>Some text</p> - lessons, tutorials</div>

Now document.getElementById("ex2").childNodes[2].childNodes[0].nodeValue; => "Some text"

like image 120
megawac Avatar answered Nov 21 '25 01:11

megawac


The childNodes property returns a collection of a node's child nodes, as a NodeList.

Tip: You can use the length property to determine the number of child nodes, then you can loop through all child nodes and extract the info you want.

In this JavaScript returns "http://coursesweb.net" because div with id ex2 have childnodes and we get its value.

like image 34
Vaibhav Parmar Avatar answered Nov 21 '25 01:11

Vaibhav Parmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!