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

梦想与她 提交于 2019-12-22 09:46:47

问题


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')

回答1:


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")')



回答2:


You can use filter for this:

var elements = $('.testdiv').filter(function(){
    return !$(this).find('a[href=\\/link3]').length;
});



回答3:


$('div.testdiv a[href^=/link3').parents();


来源:https://stackoverflow.com/questions/10669163/jquery-select-all-elements-except-one-with-specific-child-with-specific-attribu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!