Reputation: 1995
I have a HTML markup that looks like
<ul>
...
<li>
<ul class="x">
...
<a href="#"...
How can I get the parent ul.x
element from a click event hooked on the link?
this.parentNode
works if the UL is the parent element, but if it's one of the ancestors I have to use this.parentNode.parentNode
depending on how many parent elements are in between...
Can I somehow get the first UL parent?
Upvotes: 3
Views: 4517
Reputation:
For performance,
You can also use jquery on like below, jquery eventObject also has a property named delegateTarget, which could be useful in your case.
$('ul.x').on('click', 'a', function(e){
//e.delegateTarget is the parent ul of the clicked a tag
//e.target.id is the clicked a tag
alert(e.delegateTarget.id);
alert(e.target.id);
});
HTML:
<ul id='a' class="x">
<li><a id='1' href="#">A</a></li>
<li><a id='2' href="#">B</a></li>
<li><a id='3' href="#">C</a></li>
</ul>
<ul id='b' class="x">
<li><a id='11' href="#">1</a></li>
<li><a id='21' href="#">2</a></li>
<li><a id='31' href="#">3</a></li>
</ul>
In terms of performance, you are not binding the event on all the a
tags. jQuery suggests this way.
Here is the fiddle.
Upvotes: 1
Reputation: 87073
if ul.x
is direct parent of a
use this:
$('a').on('click',function(){
var ul = $(this).parent('ul.x');
});
or
$('a').on('click',function(){
var ul = $(this).closest('ul.x');
});
Upvotes: 1
Reputation: 165951
Since you've tagged the question as jQuery:
$(this).closest("ul"); //Get the first ancestor `ul`
$(this).closest("ul.x"); //Get the first ancestor `ul` with class `x`
Or, without jQuery (since your example doesn't seem to be using jQuery):
var node = this;
while(node.tagName !== "UL") {
node = node.parentNode;
}
Upvotes: 5
Reputation: 11812
Usually you would use .closest()
like:
$('a').click(function(){
var ul = $(this).closest('ul.x'); //or just closest('ul') in case you only used the x for demo purposes
});
This will go up the DOM tree and stop at the first match (your ul.x
-element).
Upvotes: 1