jQuery: select all elements of a given class, exce

2019-01-08 07:14发布

This is probably pretty simple.

I want to select all elements of a given class thisClass, except where the id is thisId.

i.e. something equivalent to (where -/minus implies remove):

$(".thisClass"-"#thisId").doAction();

6条回答
来,给爷笑一个
2楼-- · 2019-01-08 07:48

I'll just throw in a JS (ES6) answer, in case someone is looking for it:

Array.from(document.querySelectorAll(".myClass:not(#myId)")).forEach((el,i) => {
    doSomething(el);
}

Update (this may have been possible when I posted the original answer, but adding this now anyway):

document.querySelectorAll(".myClass:not(#myId)").forEach((el,i) => {
    doSomething(el);
});

This gets rid of the Array.from usage.

document.querySelectorAll returns a NodeList.
Read here to know more about how to iterate on it (and other things): https://developer.mozilla.org/en-US/docs/Web/API/NodeList

查看更多
beautiful°
3楼-- · 2019-01-08 07:50

You could use the .not function like the following examples to remove items that have an exact id, id containing a specific word, id starting with a word, etc... see http://www.w3schools.com/jquery/jquery_ref_selectors.asp for more information on jQuery selectors.

Ignore by Exact ID:

 $(".thisClass").not('[id="thisId"]').doAction();

Ignore ID's that contains the word "Id"

$(".thisClass").not('[id*="Id"]').doAction();

Ignore ID's that start with "my"

$(".thisClass").not('[id^="my"]').doAction();
查看更多
放荡不羁爱自由
4楼-- · 2019-01-08 07:52

Or take the .not() method

https://api.jquery.com/not/

$(".thisClass").not("#thisId").doAction();
查看更多
Fickle 薄情
5楼-- · 2019-01-08 07:53

Use the :not selector.

$(".thisclass:not(#thisid)").doAction();

If you have multiple ids or selectors just use the comma delimiter, in addition:

(".thisclass:not(#thisid,#thatid)").doAction();

查看更多
smile是对你的礼貌
6楼-- · 2019-01-08 08:00

$(".thisClass[id!='thisId']").doAction();

Documentation on selectors: http://api.jquery.com/category/selectors/

查看更多
成全新的幸福
7楼-- · 2019-01-08 08:05

Using the .not() method with selecting an entire element is also an option.

This way could be usefull if you want to do another action with that element directly.

$(".thisClass").not($("#thisId")[0].doAnotherAction()).doAction();
查看更多
登录 后发表回答