-4

I want to add a Class to all images except for two specific ones. Because i don't want to add that Class to the logo for example.

This is what i have now:

$('img').addClass('class_two');

The images where i don't want to add this class on are:

<img id="id_1" src="danielgotzlogo.png" alt="danielgotzlogo">
<img id="id_2" src="xxsbanner.jpg" alt="#">

But this adds it to all images. How can i not add the Class to specific ones?

Mr. Code
  • 41
  • 1
  • 5
  • 4
    Do you mean a class? I ask as `id` attributes must be unique. You cannot apply the same one to multiple elements. Also, what is the rules for identifying the images you *do not* want to put the class on? – Rory McCrossan Apr 10 '18 at 13:01
  • 1
    Define your *specific ones* and filter them. – Lece Apr 10 '18 at 13:01
  • use if statement and check for a specific rule true only for those exceptions – aMJay Apr 10 '18 at 13:02
  • @RoryMcCrossan Yeah i ment a class. – Mr. Code Apr 10 '18 at 13:03
  • What Rory said - you haven't said how you identify the two images that _won't_ get the new class. Also, please edit your question to clarify that it is indeed a class you want to add, not an ID. – Alnitak Apr 10 '18 at 13:05
  • Possible duplicate of [Negative CSS selectors](https://stackoverflow.com/questions/726493/negative-css-selectors) – apple apple Apr 10 '18 at 13:08
  • @Alnitak i'll identify them by id="id_1" and id="id_2". – Mr. Code Apr 10 '18 at 13:24

3 Answers3

2

Given the specific IDs of the two elements you don't want to affect:

$('img').not('#id1').not('#id2').addClass('myclass');

or:

$('img').not('#id1,#id2').addClass('myclass');

or:

$('img:not(#id1,#id2)').addClass('myclass');
Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

Try the following:

$("img:not(#id_1,#id_2)").addClass("class_two");

If your logo (on which you do not want to add the class) has the class logo then try then you can try the following also:

$("img:not(.logo)").addClass("class_two");

Mamun
  • 66,969
  • 9
  • 47
  • 59
1

You could write a function like this:

function _addClass(klass, to, except){
    $(to).not(except.join()).addClass(klass)
}

_addClass('class_two', 'img', ['#id_1', '#id_1'])

This will add the class 'klass' to every elements 'to' except those matching the 'except' selector.

demo: https://jsfiddle.net/xpvt214o/89314/

Oli Crt
  • 1,123
  • 1
  • 11
  • 13