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<input type="checkbox" name="N1 2AB"></label><br>
<label>E1 1AB<input type="checkbox" name="E1 1AB"></label><br>
</div>

I need to select a div from the first checkbox. Sort of

 parentNode.parentNode.getElementsByTagName("div");

But I don’t understand - this particular row selects all divs one parent over the one I need.

+3
source share
3 answers

Firstly, I think it would be easier to just put the id in the desired div, and then say document.getElementById('divId').

But if you want to do it your own way, you can perhaps debug it by checking the property first nodeNameto make sure your event is actually fired at the input, not at the label, and then checks parentNode.nodeName, etc.

+1
source

Got a solution!

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

, IE , .

. jsfiddle : http://jsfiddle.net/SLjXW/

0

Using an identifier would be easiest (as Tim Goodman says), but if you can’t (generate the DOM, don’t you know the identifier?), I would iterate over the siblings, not the parents. Something along the lines (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);
0
source

Source: https://habr.com/ru/post/1743869/


All Articles