javascript 将类添加到父元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20539906/
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
Add class to parent element
提问by Marius Djerv
I know this has been asked many times before, but I could not find anything that worked. I will need to add a class to a div that gets autogenerated over my ul.
我知道这已经被问过很多次了,但我找不到任何有用的东西。我需要将一个类添加到通过我的 ul 自动生成的 div。
This is my html code:
这是我的 html 代码:
<div class="wrapper">
<ul id="bx-pager">
<li><a><img></a></li>
<li><a><img></a></li>
</ul>
</div>
I need to add a second class to div class "wrapper", but after what I have tried I can't get it to work. I would be nice if someone can help me out with this simple task, but showing me how to do it. I don't have much experience with jQuery, but need it now.
我需要向 div 类“包装器”添加第二个类,但是在尝试之后我无法让它工作。如果有人能帮我完成这个简单的任务,但告诉我如何做,我会很好。我对 jQuery 没有太多经验,但现在需要它。
回答by Jonathan
回答by Mo.
In pure javaScript
在纯 javaScript 中
this.parentElement.classList.add('newClass');
回答by Suhas
Its simple find parent and add new class. You can use following code to find any parent and add new class.
它的简单查找父项并添加新类。您可以使用以下代码查找任何父类并添加新类。
$(this).parent().addClass('newClass');