最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery selector NOT - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question edited Jul 23, 2010 at 20:44 nicolaskruchten 27.4k8 gold badges88 silver badges103 bronze badges asked Jul 22, 2010 at 14:48 PwnnaPwnna 9,53821 gold badges67 silver badges94 bronze badges 4
  • 1 You can't have 2 elements with the same id! – nicolaskruchten Commented Jul 22, 2010 at 14:51
  • 3 @nik: Yes you can(Obama). It's just not valid and definitly not remendable. – jAndy Commented Jul 22, 2010 at 14:55
  • How will jQuery react to having multiple elements with the same ID? :) – nicolaskruchten Commented Jul 22, 2010 at 14:59
  • @njk: it will only query/select the first occurence: jsfiddle/v4wkv – jAndy Commented Jul 22, 2010 at 15:08
Add a ment  | 

2 Answers 2

Reset to default 7

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./not/ for the documentation for the not() method (first option) or http://api.jquery./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 :)

You can bine 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.

发布评论

评论列表(0)

  1. 暂无评论