Rolando
Rolando

Reputation: 62634

How do I get a selector on the specific span inside div in jquery?

Assume I have the following:

<input type="text">
<div id="listofstuff">
    <div class="anitem">
        <span class="item name">Dog</span>
        <span class="itemdescription">AboutItem1</span>
    </div> 
    <div class="anitem">
        <span class="item name">Doodle Bird</span>
        <span class="itemdescription">AboutItem2</span>
    </div>
    <div class="anitem">
       <span class="item name">Cat</span>
       <span class="itemdescription">AboutItem3</span>
    </div>
</div>

I want to use jQuery selectors to get the <div> (.anitem) that contains the <span> with the item name "Cat".

I thought it would be something like below, but it doesn't work.

$('#listofstuff').find('.anitem div span:contains("Cat")');

What am I doing wrong?

Upvotes: 2

Views: 171

Answers (4)

Brigand
Brigand

Reputation: 86240

If not the fastest, it's the most sensible.

$('#listofstuff span:contains("Cat")').parent();

demo

Upvotes: 1

Amadan
Amadan

Reputation: 198324

$('#listofstuff').find('div.anitem:has(span:contains("Cat"))')

Upvotes: 0

SpoonNZ
SpoonNZ

Reputation: 3829

$('.anitem').has('span:contains("Cat")') might get you closer

Upvotes: 2

Ry-
Ry-

Reputation: 224942

You need to use the :has pseudo-class to get an element by its descendants:

$('#listofstuff .anitem:has(span:contains("Cat"))')

Here's a demo.

Upvotes: 4

Related Questions