JQuery Find #ID, RemoveClass and AddClass
Asked Answered
C

5

27

I have the following 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 ?

I tried

jQuery('#testID2').find('.test2').replaceWith('.test3');

But this doesn't appear to work ?

Any ideas ?

Cater answered 9/3, 2010 at 7:1 Comment(0)
A
47
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.

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.

Afterheat answered 9/3, 2010 at 7:6 Comment(1)
+nudge over 1000. Nice explanation.Dealings
A
9
$('#testID2').addClass('test3').removeClass('test2');

jQuery addClass API reference

Alimentary answered 9/3, 2010 at 7:5 Comment(0)
C
5

Try this

$('#testID').addClass('nameOfClass');

or

$('#testID').removeClass('nameOfClass');
Clapper answered 9/3, 2010 at 7:4 Comment(0)
M
0

.....

$("#testID #testID2").removeClass("test2").addClass("test3");

Because you have assigned an id to img too, you can simply do this too:

$("#testID2").removeClass("test2").addClass("test3");

And finally, you can do this too:

$("#testID img").removeClass("test2").addClass("test3");
Makepeace answered 9/3, 2010 at 7:7 Comment(0)
G
0

corrected Code:

jQuery('#testID2').addClass('test3').removeClass('test2');
Greeson answered 18/6, 2013 at 10:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.