fightstarr20
fightstarr20

Reputation: 12568

jQuery - Select parent li from Div contents

I am trying to select a parent LI depending on what is inside of a div, here is where I am currently...

http://jsfiddle.net/qYdwR/1257/

<ul>
    <li>
    <div>
        Myitem
    </div>
    <div>
        John Resig
    </div>
    </li>
</ul>

$( "div:contains('John')" ).css( "text-decoration", "underline" );

This correctly underlines the div containing the word John, I now want it to apply some styling to the parent li that contains this div

Upvotes: 1

Views: 32

Answers (3)

Spork
Spork

Reputation: 1651

$( "div:contains('John')" ).css( "text-decoration", "underline" ).parent().css("background-color", "green");

Should do the trick

Upvotes: 2

Roland Mai
Roland Mai

Reputation: 31077

Use closest to travel up and find the nearest ancestor that matches the selector:

$( "div:contains('John')" ).closest('li').css("text-decoration", "underline")

Upvotes: 3

smnbbrv
smnbbrv

Reputation: 24531

Use .parents() or .parent()

$( "div:contains('John')" ).parents("li:first").css( "text-decoration", "underline" );

another way: use ":has"

$( "li:has(div:contains('John'))" ).css( "text-decoration", "underline" );

Upvotes: 2

Related Questions