jQuery: select all elements of a given class, except for a particular Id

倾然丶 夕夏残阳落幕 提交于 2019-12-17 08:16:06

问题


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();

回答1:


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();




回答2:


Or take the .not() method

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

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



回答3:


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




回答4:


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

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




回答5:


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();



回答6:


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();


来源:https://stackoverflow.com/questions/2551217/jquery-select-all-elements-of-a-given-class-except-for-a-particular-id

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