How to get to the far parent in JS? To make this code look more cool.

for(var i=0; i < carlingFox.length; ++i){ var el = sexturyFox[i].parentNode.parentNode.parentNode.parentNode el.style.background = 'red' } 

    2 answers 2

     function closest(el, cl) { var elem = el; while(elem.className != cl) { if(elem.tagName.toLowerCase() == 'html') return false; elem = elem.parentNode; } return elem; 

    }

    Arguments ate - element, cl - the class of the element to be found. If the house does not have an email with this class, returns false;

    • I would also add a check on the type of the parent: search by class name or by tag. - ling

    You can write a function like:

     function gt(node, indx) { var parent; for (var i = 0; i <= indx; i++) { node = node.parentNode; } return(node); } 

    and call by index (0 is the first parent)

     gt(sexturyFox[i], 3).style.background = 'red'; 

    for example

    • one
      1 - It is inconvenient to count indices, it is more convenient by some identifier - markuper
    • @markuper also thought about this, but there may be several identical nested ones, so it’s best to cling to the ID or class. - oburejin
    • inconvenient in any case , because if you try to bypass DOM nodes in this way, you obviously do something wrong, just add an identifier, gain in speed, convenience, readability, what else is needed? - Specter
    • This is a question for the author, not for me =) - oburejin