views:

41

answers:

4

Hi, I'm trying to perform a simple replace(); method in JavaScript where I'd like to remove every class from an HTML element except a specific one, how can I do it?

I tried this without success:

<div id="my_div" class="hello letsgo baby is_checked cool">Gordon Freeman</div>

<script>
$(document).ready(function () {
    alert ($(#my_div).attr("class").replace (/^(is_checked)$/, ""));
    // id'like it returns "is_checked" or "" to work like a boolean;
});
</script>
A: 

You want to remove every class except a specific one? You can use jQuery's attr() method and define the class specifically:

$('#my_div').attr('class','is_checked');

Here's an example of this in action: http://jsfiddle.net/decHw/

Also important to note that if you wish to select an element in jQuery by its id, you need to wrap it in quotes. You have:

$(#my_div)

It should be:

$('#my_div')
treeface
+2  A: 

You're trying to alert is_checked when it's there, right? Try using .hasClass:

$(document).ready(function () {
    if($("#my_div").hasClass("is_checked")) {
        alert("is_checked");
    }
    else {
        alert("");
    }
});

If you just want to know whether an element has a certain class on it, this returns true or false telling you exactly that:

$("#my_div").hasClass("is_checked")
Aaron
lol, I've missed this
Vittorio Vittori
A: 
$(document).ready(function () {
    if ($(this).hasClass('is_checked') {
      $(this).removeClass();
      $(this).addClass('is_checked');
    }
});
Robusto
A: 
if ($(this).hasClass('is_checked'))
    $(this).removeClass().addClass('is_checked');
else
    $(this).removeClass();
Yuriy Faktorovich