Forum Moderators: open

Message Too Old, No Replies

DOM tree question

         

stef25

7:49 pm on Aug 29, 2006 (gmt 0)

10+ Year Member



i have a div with inside nothing but two images. im using document.getElementById("testing").childNodes[0]; to get at the first image but that doesnt work. only childNodes[1] works. Firebug says that #testing has 5 childnodes and the first one is [Text] "\n"

can anyone explain why the first image isnt the first child of the div?

Bernard Marx

9:12 pm on Aug 29, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Line breaks in markup can be parsed (in some browsers) as empty text nodes, thus this DIV

<div>
<img>
</div>

..actually contains 3 child nodes.

Writing the source code all on one line can solve this, but it's inconvenient.
Instead, get the first image like so:

document.getElementById("testing").getElementsByTagName("img")[0];

--------------------------

PS. Use "*" instead of "img" to get the first child element of any kind.

stef25

9:49 pm on Aug 29, 2006 (gmt 0)

10+ Year Member



thanks for your explanation

document.getElementById("testing").getElementsByTagName("img")[0]; does indeed work in IE and FF and it targets the correct image - the first one

it seems FF takes a linebreak as a child element and IE does not. the line you proposed gets around that problem though

ive been reading about walking DOM trees all afternoon, including a Sitepoint book on dhtml and nowhere did it mention this, a bit much! Only firebug and webmasterworld provide a solution for an oh so simple dhtml script ...

thanks again