简体   繁体   中英

Get the parent HTML element of certain type with JS

My code looks like this, in closeup:

<h2>
<span class="stuff">[<a id="someid">stuff</a>]</span> <span class="moreStuff">Another test</span>
</h2>

I've found a way to select my a element, and attach an id to it. What I need to do now is select its parent <h2> element, but not the <span> element. How can I do that (JQuery allowed)?

Edit: when I retrieve the selected <a> s, I get an array of them (there's lots of these structures on my page). When I try to write myArray[someIndex].closest("h2") , it says that the element does not have a closest() method. How would I go about this?

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.

<h2>不是<a>的父级,但它是一个祖先,使用.closest()选择它

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

尝试使用.parent()来获得 DOM 树的两倍或更多级别。

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM