JQuery find closest parent link with attribute

I want to find the closest attribute link findmefrom 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 is data-findmenot a parent, but is another child of the parent, my example will not find this element. Example: http://jsfiddle.net/rjhgvxoe/

How can I make it work?

+4
source share
2 answers

You will need a selector like this:

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

This will request the closest element <li>that contains the element with the attribute data-findme. To grab the anchor from there

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

You need to use:

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

Demo

+2

All Articles