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

JqueryJquery Selectors

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

Or take the .not() method

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

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

Solution 3 - Jquery

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

Solution 4 - Jquery

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

Solution 5 - Jquery

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

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

Solution 6 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnkurView Question on Stackoverflow
Solution 1 - JqueryrahulView Answer on Stackoverflow
Solution 2 - JqueryKarl AdlerView Answer on Stackoverflow
Solution 3 - JqueryScottyGView Answer on Stackoverflow
Solution 4 - JqueryJayant BhawalView Answer on Stackoverflow
Solution 5 - JqueryAmy BView Answer on Stackoverflow
Solution 6 - JqueryNiZaView Answer on Stackoverflow