Initially, your code contains duplicate id
attributes, which is not allowed. Each id
should be unique within the document
. To address this issue, you can utilize common classes and a data
attribute to establish the relationship between the a
and div
elements. Here's an example:
<ul>
<li class="foo" data-rel="test1">Test1</li>
<li class="foo" data-rel="test2">Test2</li>
<li class="foo" data-rel="test3">Test3</li>
</ul>
<div class="content" id="test1">Test 1, okay!</div>
<div class="content" id="test2">Test 2, okay!</div>
<div class="content" id="test3">Test 4, okay!</div>
.content {
display: none;
}
$('.foo').click(function() {
$('#' + $(this).data('rel')).show().siblings('div').hide();
})
Sample implementation
If desired, you can avoid using data
attributes and id
by establishing the link based on the element's position within its container:
<ul>
<li>Test1</li>
<li>Test2</li>
<li>Test3</li>
</ul>
<div id="content-container">
<div>Test 1, okay!</div>
<div>Test 2, okay!</div>
<div>Test 4, okay!</div>
</div>
#content-container > div {
display: none;
}
$('li').click(function() {
$('#content-container').find('div').eq($(this).index()).show().siblings().hide();
})
Interactive demo
Note that although the second approach is more concise, it may lack robustness depending on the structure and potential changes in your HTML. Both methods are valid solutions, so choose what best suits your needs.