How to reference a div using an identifier contained in another element?

I have an index that, when clicked on, displays a div containing its contents.

Here is the HTML so that I can explain correctly:

<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 display its contents div, and also hide any other visible ones.

How can i do this?

Here is what I tried but stuck at this point:

 $('.index li').click(function(e) { // somehow reference the content div using: "index-" + $(this).text() }); 
+4
source share
5 answers

It looks like you are looking for:

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

Here you can see a working example: http://jsfiddle.net/ktsfs/1/

+6
source

I like Martin's solution , but if you are using HTML5, it would be nice to define the relationship between links and their content in HTML and not 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(); }); 
+3
source

Very simple:

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

Try something like this:

Give each of your index elements a class for the letter you want to use:

 <ul class="index"> <li class="A">A</li> <li class="B">B</li> <li class="C">C</li> </ul> <div id="index-contents"> <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> </div> 

And then you can find / show the contents of the index with

 $('.index li').click(function(e) { // Hide all $('#index-contents .hide').hide(); // Find the class of the clicked index item var index = $(this).attr('class'); // Show the index contents $('#index-contents').children('#index-'+index).show(); }); 

http://jsfiddle.net/uS4Cs/1/

0
source

Demo http://jsfiddle.net/CzzG8/

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

Source: https://habr.com/ru/post/1386951/


All Articles