Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: select all elements except one with specific child with specific attribute

Assuming I have something like this:

<div class="testdiv">
    <a href="/link1">link 1</a>
</div>
<div class="testdiv">
    <a href="/link2">link 2</a>
</div>
<div class="testdiv">
    <a href="/link3">link 3</a>
</div>
<div class="testdiv">
    <a href="/link4">link 4</a>
</div>

Now I want select all <div>s of class testdiv except the div that has a child <a> with attribute href="/link3", how to do that with jQuery?

I know I can do this:

$('div.testdiv')
like image 854
evilReiko Avatar asked May 23 '26 18:05

evilReiko


1 Answers

With :not + :has it can be done easily with one selector:

$('div.testdiv:not(:has(a[href="/link3"]))')

If you don't quote the value in the attribute ("CSS identifiers") you need to escape the slash(/) with two backslashes (\\):

$('div.testdiv:not(:has(a[href=\\/link3]))')

Live DEMO

If There can be only one anchor in a div, you can use this:

$('div.testdiv:has(a[href!="\\/link3")')
like image 111
gdoron is supporting Monica Avatar answered May 25 '26 07:05

gdoron is supporting Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!