Skip to content Skip to sidebar Skip to footer

Get The Parent Html Element Of Certain Type With Js

My code looks like this, in closeup:

[stuff]Another test

Solution 1:

One ways is to use the .parents() method of jQuery, with a selector. Something like this.

$("#someid").parents("h2");

Update:

You can use the .closest() method with a selector, to only get the closest parent that match the selector.

$("#someid").closest("h2");

Update 2:

It would be a bit more work to do it with plain JavaScript. Not sure if it is the most efficient, but one way would be to select the element with document.getElementById() and then get a reference to its parent through the parentNode property. Then you would have to check if it is an h2 element, and if not, look at that elements parent node, and so on.

You could check the jQuery source and see how they have implemented the closest method.

Solution 2:

The <h2> is not the parent of the <a> but it is an ancestor, use .closest() to select it

$("#someid").closest("h2");

Solution 3:

try use .parent() for get exactly double or more level up the DOM tree.

$("#someid").parent().parent();

Solution 4:

I just needed the same thing. here a vanilla javascript variant:

functionfindParent(startElement, tagName) {
  let currentElm = startElement;
  while (currentElm != document.body) {
    if (currentElm.tagName.toLowerCase() == tagName.toLowerCase()) { return currentElm; }
    currentElm = currentElm.parentElement;
  }
  returnfalse;
}

Post a Comment for "Get The Parent Html Element Of Certain Type With Js"