Wim Mertens Wim Mertens - 2 months ago 7
jQuery Question

link with class name to target div with an id same as the class name of the link

Basically I have a list of links with class names and a container with divs which ids are the same as the class names of the links.

<ul>
<li><a class="table-names">Names</a></li>
<li><a class="table-addresses">Addresses</a></li>
<li><a class="table-phone">Phone Numbers</a></li>
</ul>

<div class="container">
<div id="table-names" class="selected">...</div>
<div id="table-addresses">...</div>
<div id="table-phone">...</div>
</div>


If I click on the link "table-names" then
id="table-names"
needs to have the class
selected
added, and the siblings need to have the class "selected" removed.

Here's my jquery:

$('ul li a').click(function () {
$(this).parent('li').addClass("selected").siblings("li").removeClass("selected");
$('.container div').removeClass("selected");
$('#' + $(this).className()).addClass("selected");
});


This is somehow not working although I believe the code is correct. What am I doing wrong?

Answer

$(this).className() is not valid, you need to change it to $(this).attr('class') or this.className

$('ul li a').click(function () {
    $(this).parent('li').addClass("selected").siblings("li").removeClass("selected");
    $('.container div').removeClass("selected");
    $('#' + $(this).attr('class')).addClass("selected");
});
Comments