Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a div using id contained in another element?

I have an alphabetical index that when clicked unhides a div that contains it's content.

Here is the HTML so I can explain properly:

<ul class="index">
    <li>A</li>
    <li>B</li>
    <li>C</li>
</ul>

<div id="index-A" class="hide">A contents</div>
<div id="index-B" class="hide">B contents</div>
<div id="index-C" class="hide">C contents</div>

When a letter is clicked, I want to unhide it's content div and also hide any other ones that are visible.

How could I do that?

Here is what I have been trying, but am stuck at this point:

$('.index li').click(function(e) {
    // somehow reference the content div using: "index-" + $(this).text()
});
like image 740
Jacob Avatar asked Jan 18 '23 00:01

Jacob


2 Answers

Sounds like you are looking for this:

$('.index li').click(function(e) {
   var div =  $('#index-'+  $(this).text()).show();
   div.siblings('div').hide();
});

You can see a working example here: http://jsfiddle.net/ktsfs/1/

like image 83
Martin Jespersen Avatar answered Apr 29 '23 03:04

Martin Jespersen


I like Martin's solution, but if you're using HTML5 it'd be nice to define the relationship between the links and their content in HTML rather than in Javascript:

<ul class="index">
    <li data-show="#index-A">A</li>
    <li data-show="#index-B">B</li>
    <li data-show="#index-C">C</li>
</ul>

<div id="index-A" class="hide">A contents</div>
<div id="index-B" class="hide">B contents</div>
<div id="index-C" class="hide">C contents</div>

Javascript:

$(".index li").click(function(e) {
   var div = $($(this).data("show")).show();
   div.siblings("div").hide();
});
like image 29
Andrew Marshall Avatar answered Apr 29 '23 03:04

Andrew Marshall