views:

140

answers:

3

I have about thousand DIV tags structured this way:

<div id="1">
    <div class="1"></div>
    <div class="2"></div>
    ...
</div>

<div id="2">
    <div class="1"></div>
    <div class="2"></div>
    ...
</div>

If I want to now access a particular node, say 'div#10 div.5' - what is the fastest way to do it using javascript DOM traversal? I already have the index values "10" and "5" - I am just looking for the fastest way to achieve this.

Thanks a lot.

+2  A: 

using jquery:

alert($("#10 > .5").html());
Thomas Stock
I would second that. It is fastest at least in terms of grasping the semantics of the code.
SeasonedCoder
+2  A: 

Without validation and assuming the child nodes are the only nodes and all in sequence;

document.getElementById('10').childNodes[4];

Watch out for whitespace that becomes a node https://developer.mozilla.org/En/Whitespace_in_the_DOM

Dave Anderson
Yes, thanks, I think that's how fast it can get! Although it's unfair to compare pure JS to any specific JS library, in this case, pure JS is the best as far as speed is concerned!
+3  A: 

If you've got about 1000 DIVs I assume this is auto generated html?

If so, is there any reason why you can't add an id to the inner DIVs too?

<div id="1">
    <div id="1.1" class="1"></div>
    <div id="1.2" class="2"></div>
    ...
</div>

<div id="2">
    <div id="2.1" class="1"></div>
    <div id="2.2" class="2"></div>
    ...
</div>

Then you can just use getElementById and not have to worry about ordering or spacing etc.

Since element ids have to be unique on the page then this should always be the fastest way to look up the element.

Stringent Software
Oh yes! Thanks, this idea never occurred to me!