Skip to content Skip to sidebar Skip to footer

How To Add A Class To All Images Except Specific Ones With Js

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

Solution 1:

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

Solution 2:

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

Solution 3:

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/

Post a Comment for "How To Add A Class To All Images Except Specific Ones With Js"