JQuery 查找 #ID、RemoveClass 和 AddClass
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2407179/
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
JQuery Find #ID, RemoveClass and AddClass
提问by Tom
I have the following HTML
我有以下 HTML
<div id="testID" class="test1">
<img id="testID2" class="test2" alt="" src="some-image.gif" />
</div>
I basically want to get to #testID2 and replace .test2 class with .test3 class ?
我基本上想到达 #testID2 并将 .test2 类替换为 .test3 类?
I tried
我试过
jQuery('#testID2').find('.test2').replaceWith('.test3');
But this doesn't appear to work ?
但这似乎不起作用?
Any ideas ?
有任何想法吗 ?
回答by Dominic Barnes
jQuery('#testID2').find('.test2').replaceWith('.test3');
Semantically, you are selecting the element with the ID testID2
, then you are looking for any descendent elements with the class test2
(does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3
) that also do not exist.
从语义上讲,您正在选择具有 ID 的元素testID2
,然后您正在寻找具有该类的任何后代元素test2
(不存在),然后您将该元素替换为另一个元素(页面中具有该类的任何地方的元素test3
)也可以不存在。
You need to do this:
你需要这样做:
jQuery('#testID2').addClass('test3').removeClass('test2');
This selects the element with the ID testID2
, then adds the class test3
to it. Last, it removes the class test2
from that element.
这将选择具有 ID 的元素testID2
,然后test3
向其中添加类。最后,它test2
从该元素中删除类。
回答by Amarghosh
$('#testID2').addClass('test3').removeClass('test2');
jQuery addClassAPI reference
jQuery addClassAPI 参考
回答by Hyman
Try this
尝试这个
$('#testID').addClass('nameOfClass');
or
或者
$('#testID').removeClass('nameOfClass');
回答by Sarfraz
.....
.....
$("#testID #testID2").removeClass("test2").addClass("test3");
Because you have assigned an id to img too, you can simply do this too:
因为您也为 img 分配了一个 id,所以您也可以简单地这样做:
$("#testID2").removeClass("test2").addClass("test3");
And finally, you can do this too:
最后,你也可以这样做:
$("#testID img").removeClass("test2").addClass("test3");
回答by Jibu K
corrected Code:
更正的代码:
jQuery('#testID2').addClass('test3').removeClass('test2');