PDA

View Full Version : How to access the childNodes value



d4d4n9
07-26-2013, 04:20 PM
Hi All,
Need to access the value of a childNodes in the following code:


<HTML>
<HEAD>
<TITLE>My Document</TITLE>
</HEAD>
<BODY BGCOLOR="lightgreen">
<DIV ID="myDiv">Testing</DIV>
<script>
var values=document.childNodes[1].childNodes[0].innerText;
document.write(values);
</script>
</BODY>
</HTML>

I need the way to get the value of "myDiv".
When I loaded the code in Chrome browser, I got the following error: "Uncaught TypeError: Cannot read property 'childNodes' of undefined"
Please, what should the correct syntax?
Thanks in advance.

Regards,
d4d4n9

Beverleyh
07-26-2013, 04:53 PM
I'm not a JavaScript expert but if you're trying to access the content inside the div, would getElementById be better?
var values = document.getElementById("myDiv").innerHTML;

traq
07-26-2013, 08:31 PM
document.childNodes[1] does not exist (and so, is "undefined"). document has only one child: <html>

So, <html> is node #0 of the document; and <body> is actually node #2 of <html> (#0 is the <head>, #1 is the carriage return (\r\n) between the <head> and <body>).

As you may have realized at this point, Beverley is right - getElementById would be a much easier and more robust way to approach this task.

d4d4n9
07-26-2013, 09:31 PM
@Beverleyh and traq
Thanks for your responses. Right, it's easier to use Beverleyh's way.
It's really nice.

jscheuer1
07-27-2013, 01:23 AM
You can also use:


document.documentElement

for <html>

and:


document.body

for <body>

And, if you're not interested in text nodes:


document.getElementsByTagName('*')

Will get you a node list of all of the tags in the document. Similarly you can go after specific tags:


document.getElementsByTagName('head')[0]

will get you the head, Or:


document.getElementsByTagName('div')

Will get you all of the divs, which you could then iterate over to find the one you want. Or if you already know, refer to it by its index, ex:


document.getElementsByTagName('div')[5]

Which would be the 6th - if it exists.

It really all depends upon what you're after, and how best to get a reference to it. Sometimes there are multiple ways. Well almost always, but sometimes two or more of these methods will be just as good as the other.