Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Find #ID, RemoveClass and AddClass

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 ?

like image 822
Tom Avatar asked Mar 09 '10 07:03

Tom


People also ask

What is find () in jQuery?

The find() is an inbuilt method in jQuery which is used to find all the descendant elements of the selected element. It will traverse all the way down to the last leaf of the selected element in the DOM tree. Syntax: $(selector).find()

What does $() mean in jQuery?

In jQuery, the $ sign is just an alias to jQuery() , then an alias for a function. This page reports: Basic syntax is: $(selector).action() A dollar sign to define jQuery.

Does find return jQuery object?

find() returns an object even when there's no matching child element in the DOM.

How can get li id value in jQuery?

ready(function() { $('#list li'). click(function() { alert($(this). attr("id")); alert($(this). text()); }); });


3 Answers

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.

like image 166
Dominic Barnes Avatar answered Oct 12 '22 05:10

Dominic Barnes


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

jQuery addClass API reference

like image 41
Amarghosh Avatar answered Oct 12 '22 05:10

Amarghosh


Try this

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

or

$('#testID').removeClass('nameOfClass');
like image 4
Jack Avatar answered Oct 12 '22 04:10

Jack