How to add a class to all images except specific ones with JS

你离开我真会死。 提交于 2019-12-14 00:09:59

问题


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

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