w35l3y
w35l3y

Reputation: 8783

Iterate through parent elements containing specific descendent node

I would like to iterate only through parent elements that contain a specific element as descendant node.

For example:

<div class="field">
   <input type="text" />
</div>
<div class="field">
   <input type="button" />
</div>
<div class="field">
   <input type="text" />
</div>

I know that using xpath, it could be accomplished by using div[@class = 'field' and input[@type = 'text']]

With jQuery, I would like to use something similar to div.field[input[type = 'text']].

The nearest option that I know is div.field > input[type = 'text'], but this way I would be iterating through inputs instead of divs.

Thanks in advance

Upvotes: 0

Views: 4303

Answers (2)

MayThrow
MayThrow

Reputation: 2201

You can use .parents()

$('input[type=text]').parents('.field').each(function(){
//do your stuff
})

example - http://jsfiddle.net/dYKRz/

Upvotes: 0

Blender
Blender

Reputation: 298562

You can use jQuery's :has() pseudo-selector:

$('.field:has(.text)')

Since it's a non-standard selector, it'll be slow compared to regular selectors, so keep that in mind if you're iterating over a ton of elements.

Upvotes: 4

Related Questions