Reputation: 5919
I need to get the ID of the "parents parent adjacent" element. I've come so far that I can select the element that contains the ID. Now I just need to output the ID.
jQuery:
$(function(){
var a = $('.function').closest('li').find('a:first').attr('id');
console.log(a);
});
HTML:
<ul>
<li>
<a id="get-this-ID-1">
Link 1.
</a>
<div>
<div class="function">
Function 1 here.
</div>
<a>Link2 1.</a>
</div>
</li>
<li>
<a id="get-this-ID-2">
Link 2.
</a>
<div>
<div class="function">
Function 2 here.
</div>
<a>Link2 2.</a>
</div>
</li>
<li>
<a id="get-this-ID-3">
Link 3.
</a>
<div>
<div class="function">
Function 3 here.
</div>
<a>Link2 3.</a>
</div>
</li>
</ul>
Upvotes: 0
Views: 52
Reputation: 9637
Try it: use map()
var a = $('.function').map(function () {
return $(this).closest("li").find(" > a")[0].id;
}).get();
Upvotes: 1
Reputation: 144719
You are on the right track. The issue is attr
returns value of the first element in the collection. You should iterate through the collection and get the ID of each element individually.
Here is an example using map
method for generating an array of IDs:
var a = $('.function').closest('li').find('a:first').map(function() {
return this.id;
}).get();
You could also use the :has
selector:
$('li:has(.function)').children('a').each(function() {
console.log(this.id);
});
Upvotes: 1
Reputation: 167212
Can you try changing from first
to first-child
:
$(function () {
var a = $('.function').closest('li').find('a:first-child').attr('id');
console.log(a);
});
Fiddle: http://jsfiddle.net/ztuttzuL/3/
Upvotes: 0