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.Update:
You can use the
.closest()method with a selector, to only get the closest parent that match the selector.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 theparentNodeproperty. Then you would have to check if it is anh2element, 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.