jQuery find closest parent link with attribute
Asked Answered
P

2

13

I'd like to find the closest link with attribute findme from a children .startpoint. Structure:

<ul>
    <li><a href="#">Point one</a></li>
    <li><a href="#" data-findme="yipi">Point one</a>
        <ul>
            <li><a href="#">Hello</a></li>
            <li><a href="#">Hello</a>
                <ul>
                    <li><a href="#" class="startpoint">My Startpoint</a></li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

JavaScript (jQuery):

$(document).ready(function(){
    console.log(
        $('.startpoint').closest("*[data-findme]")
    );
});

Since the problem is, that the element data-findme is not a a parent element instead it is another child of a parent, my example will not find the element. The example: http://jsfiddle.net/rjhgvxoe/

How can I get it to work?

Posterior answered 16/1, 2015 at 13:16 Comment(0)
M
21

You would need a selector like this:

$('.startpoint').closest("li:has(*[data-findme])")

That would query for the closest <li> element which contains an element with the attribute data-findme. To grab the anchor from there

$('.startpoint').closest("li:has(*[data-findme])").children('[data-findme]')
Margo answered 16/1, 2015 at 13:22 Comment(1)
The asterisk is not needed. This works fine: $('.startpoint').closest('li:has([data-findme])') Also not sure why you switch between single and double ticks. Where possible, use single.Coontie
S
5

You need to use:

 $('.startpoint').closest("ul").find('[data-findme]')

Demo

Sludgy answered 16/1, 2015 at 13:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.