jQuery javascript 将类添加到特定 div 中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19068771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:08:27  来源:igfitidea点击:

javascript add class to an element in a specific div

javascriptjquerycssaddclass

提问by Kevin Lloyd Bernal

So I have this arrangement in my page:

所以我在我的页面中有这样的安排:

<div class="food">

    <div>
        <a href="#" class></a>
        <a href="#" class></a>
    </div>

    <div>
        <a href="#" class></a>
        <a href="#" class></a>
    </div>

</div>

How do I add a class to all the a elements inside my div.food? What is the shortest and quickest way to implement this?

如何向 div.food 中的所有 a 元素添加一个类?实现这个的最短和最快的方法是什么?

Thanks!

谢谢!

回答by Tushar Gupta - curioustushar

To add class to all atag in div with class food

a使用类将类添加到div 中的所有标签food

$('div.food a').addClass('className');

or

或者

As commented by A. Wolff.find()is faster

正如A. Wolff评论的那样.find()更快

$('div.food').find('a').addClass('className');

or

或者

To add class to all elements in div with class food

使用类向 div 中的所有元素添加类 food

$('div.food *').addClass('className');

or

或者

$('div.food').find('*').addClass('className');

.addClass()

.addClass()

.find()

。找()

also read .removeClass()

另请阅读.removeClass()

回答by lvarayut

JQuery comes with addClass() and removeClass() to add or remove CSS class dynamically. For example,

JQuery 带有 addClass() 和 removeClass() 来动态添加或删除 CSS 类。例如,

$(‘.food′).addClass(‘ClassName');– Add a “ClassName' css class to elements that contain class of food

$(‘.food′).addClass(‘ClassName');– 将“ClassName”css 类添加到包含类的元素 food

If you want to remove a class from your div, you can use the following:

如果要从 div 中删除类,可以使用以下命令:

$(‘.food′).removeClass(‘ClassName');- Remove a “ClassName' css class from elements that contain class of food

$(‘.food′).removeClass(‘ClassName');- 从包含类的元素中删除“ClassName”css 类 food

回答by mindfullsilence

If you don't want to use jQuery:

如果您不想使用 jQuery:

var links = document.querySelectorAll('.food a');
[].forEach.call(links, function(item) {
  item.classList.add('myClass');
});

回答by Suresh

Add a class in specific div:

在特定的div中添加一个类:

$("#divData").addClass("className");

Remove a class in specific div:

删除特定 div 中的类:

$( "#divData" ).removeClass( "className" );