Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
197
rated 0 times [  200] [ 3]  / answers: 1 / hits: 29022  / 12 Years ago, fri, october 12, 2012, 12:00:00

Please take a look at the snippet below:



<div>
<div></div>
<div><!-- my target node -->
<div><!-- not my target node -->
<img /><!-- my source node -->
</div>
</div>
</div>


As you can see the img-elment has two enclosing divs. I want the first of those two enclosing divs to be considered the real parent (the one I need to find) of the img-elment because it has a brother div before so the search ends and the brother div and the outer enclosing div are ignored.



In the case there are no siblings at all, the outer div has to be yielded; in the case the element is not enclosed, the element itself has to be yielded.



I just would like to know how to target the element as I explained via JavaScript.


More From » dom

 Answers
27

So it sounds like you want the first ancestor that has siblings elements. If so, you can do it like this:



var parent = img.parentNode;

while (parent && !parent.previousElementSibling && !parent.nextElementSibling) {
parent = parent.parentNode;
}


Or perhaps more appropriately written as a do-while loop:



do {
var parent = img.parentNode;
} while (parent && !parent.previousElementSibling && !parent.nextElementSibling);


So the loop will end when it finds one with at least one sibling element, or when it runs out of ancestors.



If you know if the sibling comes before or after the parent, you can just test for one or the other.






Also note that you'll need a shim for the ***ElementSibling properties if you're supporting legacy browsers.



You can make a function that will do this:



function prevElement(el) {
while ((el = el.previousSibling) && el.nodeType !== 1) {
// nothing needed here
}

return el;
}

function nextElement(el) {
while ((el = el.nextSibling) && el.nodeType !== 1) {
// nothing needed here
}

return el;
}


Then use the functions like this:



do {
var parent = img.parentNode;
} while (parent && !prevElement(parent) && !nextElement(parent));

[#82588] Thursday, October 11, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alyssiat

Total Points: 608
Total Questions: 102
Total Answers: 101

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
;