pooyan pooyan - 7 months ago 11
HTML Question

select an element that its closest parent with special attribute has special value

I want to select an element that its closest parent with special attribute has special value. For example, in the bellow code I want to select an element that has att2="sp" and it's closest element that has an "att1" attribute, has value equal to "first_div".

<div att1="first_div">
<div att1="sec_div">
<span att2="sp">
</span>
</div>
<div>
<span att2="sp">
</span>
</div>
</div>

Answer

How about just a CSS selector that can then obviously be used in jQuery as well.

[att1=first_div] :not([att1]) [att2=sp], [att1=first_div] > [att2=sp]

should do the trick? See the fiddle for reference.

In jQuery terms,

var $el = $('[att1=first_div] :not([att1]) [att2=sp], [att1=first_div] > [att2=sp]');