jQuery selector NOT

依然范特西╮ 提交于 2019-12-12 01:26:52

问题


How do i select everything BUT the element with an id?

<div id="test">
<p id="test"></p>
<p></p>
<p></p>
</div>

I want to be able to select the second and third


回答1:


You can't have 2 elements with the id "test" but if the code was as follows:

<div id="test">
<p id="test2"></p>
<p></p>
<p></p>
</div>

then you could use

$("#test p").not("#test2")

or

$("#test p:not(#test2)")

to select just the other two paragraphs.

See http://api.jquery.com/not/ for the documentation for the not() method (first option) or http://api.jquery.com/not-selector/ for the :not() selector (second option).

Note: this won't select "everything" but rather the second and third paragraph elements. I assume that's what you meant :)




回答2:


You can combine the :not() and has-attribute selectors, like this:

$(":not([id])")

A few notes though, you currently have 2 elements with the same ID, this is invalid because IDs should be unique. Also you shouldn't use the selector exactly as I have it above, it should be within something, for example $("#test :not([id])") to narrow it down ... it's very expensive otherwise.



来源:https://stackoverflow.com/questions/3310134/jquery-selector-not

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