Swap class w/jQuery
How can I make a conditional swap with jQuery on click. If certain class is present swap it to another, for exam开发者_StackOverflowple swap class "A" to "B".
<a href="#" id="clickMe"><span class="A"></span>link</a>
I've been trying this but it does not seem to work:
$(this).closest("span").toggleClass("A,B");
What am I missing?
.closest()
goes up the DOM tree, not down.
Use .children()
or .find()
.
$(function ()
{
$('#clickMe').click(function ()
{
$(this).children('span').toggleClass('a b');
return false; // don't follow the link
});
});
.toggleClass()
expects multiple class names to be separated by spaces, not commas.
If you only want the class swap to happen once:
$(function ()
{
$('#clickMe').click(function ()
{
var $span = $(this).children('span:first');
$span.toggleClass('a b', $span.hasClass('a'));
return false; // don't follow the link
});
});
$(this).closest("span").removeClass("A").addClass("B");
Edit: the above will forcibly replace class A with class B. I think what you're looking for is to toggle between A and B every time the code runs, correct? Try:
$(this).closest("span").toggleClass("A B");
精彩评论