开发者

Changing ClassName in jQuery

I know we can do many things like changing the current styles of an element, or changing its text etc. But, how can we change the name of the class using jQuery?

For example, the following开发者_如何转开发 CSS file has two different styles:

.roundedCorners {
  /* code for roundedCorners */
}

.NotSoRoundedCorners {
  /* code for NotSoRoundedCorners */
}

And the button looks like:

<input type="submit" class="NotSoRoundedCorners" value="Turn me on!" />

I know we can directly change its styles with a simple jQuery snip like this:

$('.closer').css({'visibility': 'hidden'}, 1000); // ETC.

But, what if there are many styles to change for the one element. Why not just have 2 style definitions in the CSS file, and when we need to change the style, just change the Class name of the element to the other style?


You should invoke jQuery's .toggleClass()help method.

Using that, you can explicitly remove and add a class to a node, leaving other classes untouched.

$('.closer').toggleClass('roundedCorners NotSoRoundedCornders');

Many guys here suggested to use .attr(), but that would replace the whole className attribute and therefore would overwrite/remove any given css class. I don't think thats the way to go.


Yes. By using the attr method.

$('.NotSoRoundedCorners').attr('class', 'RoundedCorners');


$('#yourid').removeClass("NotSoRoundedCorners").addClass("roundedCorners");


$('.NotSoRoundedCorners').attr('class', 'RoundedCorners');


you can use:

$('.closer').toggleClass('roundedCorners').toggleClass('NotSoRoundedCorners')

or

$('.closer').removeClass('roundedCorners');
$('.closer').addClass('NotSoRoundedCorners')


Really, why not?

$('.closer').addClass("roundedCorners);
$('.closer').removeClass("NotSoRoundedCorners );


$('.closer').removeClass('roundedCorners');
$('.closer').addClass('NotSoRoundedCorners')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜