Jake Martinez
Jake Martinez

Reputation: 55

jQuery - adding and removing classes

I'm trying to make it so that there is a default tab, and when another is clicked, it takes the class off of that tab and onto the one that is clicked.

Here's the HTML that I have:

<div id="rightWrap">
    <div id="headStep"><span class="titleSub">Workers</span></div>
    <center>
    <br>
    <a href="../about/?s=architect"><table class="highlight">
    </table></a>
    <br>
    <a href="../about/?s=broker"><table class="">
    </table></a>
    <br>
    <a href="../about/?s=operator"><table class="">
    </table></a>
    <br>
    <a href="../about/?s=consultant"><table class="">
    </table></a>
    </center>
</div>

And the JavaScript:

$(document).ready(function() {
    $('#rightWrap a table').click(function(){
    $(this).addClass('highlight').siblings().removeClass('highlight');
});
});

Upvotes: 0

Views: 104

Answers (2)

Ram
Ram

Reputation: 144739

Your tables are not siblings.

$(document).ready(function() {
    $('#rightWrap a table').click(function(){
        var $this = $(this);
        $this.parent().siblings('a').find('table').removeClass('highlight');
        $this.addClass('highlight');     
    });
});

Note that if the doctype of the page is not HTML5, wrapping the tables with <a> elements makes your document invalid.

Upvotes: 4

jfriend00
jfriend00

Reputation: 708206

I think you can simplify it to this;

$(document).ready(function() {
    $('#rightWrap a table').click(function(){
        $('#rightWrap').find('.highlight').removeClass('highlight');
        $(this).addClass('highlight');     
    });
});

Your HTML also needs some serious work. Why the empty tables?

Upvotes: 1

Related Questions