问题
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?
回答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');
回答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");
回答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/
来源:https://stackoverflow.com/questions/49754389/how-to-add-a-class-to-all-images-except-specific-ones-with-js