views:

57

answers:

4

Assuming I have <ul class="myList verticalList"> how can I change the value of verticalList using jquery?

A: 

There is no need to change the values of verticleLIst , you can add your required properties through

$('verticleList').css() , it will automatically overwrite the values.

gov
firstly, unless you have invented your own 'verticleList' tag, that `$('verticleList')` selector won't match anything, secondly if what he wants to do is change the class, its much better to use classes than modify the style attribute, which is what the `.css` function does
tobyodavies
+14  A: 

Try a combination of addClass and removeClass

$(selector).removeClass('verticleList').addClass('newClass');

Also, did you mean: vertical

Ken Browning
+1 for "vertical"
Peter Ajtai
Thanks Ken, it turns out this is not what I needed, although your answer was very helpful. I'm using this for a star rating widget and the class name is dynamic, so I'm never quite sure which class to remove. Is there a way to clear all of the classes and set them again? I can use add class to set them, but not sure what to do about removing existing classes...
Mel
@Mel - You can have variables for remove and add class, or even a callback. To clear all and add one just do, `.attr("class","theOnlyClass")` - or to clear `.attr("class","")`.
Peter Ajtai
Peter's right. You can also use `.removeAttr('class')`
Ken Browning
+2  A: 

I thnik what you want to do is remove that class and change to another? see addClass and removeClass

$('.verticalList').addClass('foo').removeClass('verticalList') 

P.S. I've corrected spelling of 'vertical' in this version

tobyodavies
+2  A: 

There are several functions that you can use to manipulate an element class.

toggleClass adds a class on the element if it doesn't exists. If it exists then it's removed.

$(".myList").toggleClass("verticleList");

addClass insert the class on the element. If the class already exists it does nothing.

$(".myList").addClass("aClass");

removeClass remove the class from the element. If the class doesn't exists it does nothing.

$(".myList").removeClass("aClass");

hasClass returns true or false if the element has or not a class.

$(".myList").hasClass("aClass");

You can also change the class modifying the attribute (.attr) class which may not be recommended.

BrunoLM
Bruno, thanks a lot. Actually, .attr has done the trick for me since in the end I need to clear existing classes (the class name was a variable for I had no way of knowing what it was going to be--thus clearing and reseting was the best option). Can you elaborate more on why .attr is not reccommended?
Mel
@Mel: If you use `element.attr("class", "x")` it will erase all values of `class` attribute and set the value to `x`. If you want to add/remove a class using it you have to be sure the element has no other classes that might be used by some script. It's just more simple to use the functions made to manipulate the element class.
BrunoLM