How to get the parent node of an element when the parent has siblings?
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));