Getting the correct node
I have this structure in my dom:
<label>London<input type="checkbox" name="London"></label><br>
<div class="innerpost">
<label>N1 2AB<inp开发者_运维技巧ut 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.
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.
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);
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/
精彩评论