tags:

views:

48

answers:

3

Hello

I have this structure in my dom:

<label>London<input type="checkbox" name="London"></label><br>
<div class="innerpost">
<label>N1 2AB<input type="checkbox" name="N1 2AB"></label><br>
<label>E1 1AB<input type="checkbox" name="E1 1AB"></label><br>
</div>

I need a way to select the div from the first checkbox. Something like

 parentNode.parentNode.getElementsByTagName("div");

But I'm not getting it right - that particular line selects all the divs one parent above the one I need.

A: 

Got the solution!

var div = element.parentNode.nextSibling.nextSibling;
while (!div.tagName) div = div.nextSibling;

The second line is needed because IE doesn't count text nodes, but other browsers do.

See this jsfiddle for testing: http://jsfiddle.net/SLjXW/

Vincent
No because (if I'm understanding correctly) he's trying to get the div from the checkbox that's outside the div
Tim Goodman
As far as I can see, that selects the form element. I'm after the div immediately after the London input, not the parent.
YsoL8
I'm sorry. I'll try to find a right solution.
Vincent
+1  A: 

First, I think it would be easiest to just put an id on the desired div, and then say document.getElementById('divId').

But if you want to do it your way, you can probably debug this by first checking the nodeName property to make sure your event is really being called on the input and not the label, then checking parentNode.nodeName, etc.

Tim Goodman
I'd love to, but I'm generating the form dynamically and I'd end up with multiple divs with the same id. I suppose I could add numbers to the class name and attempt to calulate what the div id would be from a given checkbox. Not sure about that.
YsoL8
You'd want to increment the ID, not the classname. We've done this sort of thing before. The "London" checkbox might be id="city_18" and the div could be `<div class="innerpost" id="inner_18">`We then split on the underscore to get the ID of 18 for the city, then `getElementById("inner_"+cityId)`
Stephen P
does the numbering need to start at 0 or 1?
YsoL8
Got Stephen P's solution running smoothly. Thanks everyone for your suggestions!
YsoL8
A: 

Using an ID would be easiest (as Tim Goodman says) but if you can't (generated DOM, don't know the ID?) I'd loop through sibling nodes, not parents. Something along the lines of (pseudo-code):

var sib = eventNode; // start at the checkbox where the event took place
var found = false;
do {
    sib = sib.nextSibling;
    // see if this is the div with class innerpost
    // it could be a textnode, you can't assume the immediate sibling is the div
    if (sib.tagName == 'DIV' && sib.className.match('innerpost') {
        found = true;
        break;
    }
} while (sib);
Stephen P
I couldn't see the right class as far a 6 nextSibling
YsoL8