Milind Rasal
Milind Rasal

Reputation: 19

Jquery on click of li tag ID show reliative Div which has ID

I am new to jquery. On click of li tag which has an ID I need to show the relative div which has an ID. For e.g. on click of anchor tag ID note_1, I need to show of content of div ID notContent_1.

Following is my code.

 <ul>
    <li id="note_1">1</li>
    <li id="note_2">2</li>
    <li id="note_3">3</li>
    <li id="note_4">4</li>
</ul>
<div>
    <div id="notContent_1">A</div>
    <div id="notContent_2">B</div>
    <div id="notContent_3">C</div>
    <div id="notContent_4">d</div>
</div>

On click of each li tag I need to show relative ID's div. I don't want to write a method for each li tag.

Upvotes: 0

Views: 4378

Answers (5)

LeGEC
LeGEC

Reputation: 51790

If you want simple links, there is a pure html solution :

<ul id="links">
    <li id="note_1"><a href="#notContent_1">1</a></li>
    <li id="note_2"><a href="#notContent_2">2</a></li>
    <li id="note_3"><a href="#notContent_3">3</a></li>
    <li id="note_4"><a href="#notContent_4">4</a></li>
</ul>
<div id="notContent">
    <div id="notContent_1">A</div>
    <div id="notContent_2">B</div>
    <div id="notContent_3">C</div>
    <div id="notContent_4">d</div>
</div>

If you want to hide the other divs and show the "selected" one, you can add some javascript :

$('#links').on('click', 'a', function(e){
  e.preventDefault();

  $('#notContent div').hide();
  $( $(this).attr('href') ).show();
});

If you want to have tabs or accodions, use an appropriate library (e.g. jquery-ui, bootstrap, ... )

Upvotes: 0

Anton
Anton

Reputation: 32581

Try this

$('ul li').on('click', function () {
    $('div#notContent_' + $(this).text()).show().siblings().hide();
});

DEMO

Edit just saw, this is considering that your list text is actually 1-4

If the text is not 1-4, you could add class to the div containing the elemens and use index and eq() like this

$('.tab-content div:eq('+$(this).index()+')').show().siblings().hide();

DEMO

Upvotes: 2

Somnath Kharat
Somnath Kharat

Reputation: 3600

You can also do with this: Child Selector

    $('ul > li').on('click', function () {
        $('div#notContent_' + $(this).text()).show();
    });

DEMO

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

You can do this for example :

$('li[id^="note_"]').click(function(){
    $('[id^="notContent_"]').hide(); // hide the other divs
    $('#notContent_'+this.id.slice(5)).show();
});

This uses the "attribute starts with" selector.

Upvotes: 5

Alex
Alex

Reputation: 1304

Try this solution

$(document).ready(function(){

    //detecting and handling click on list element
    $('li').click(function(){

        var id = $(this).attr('id');
        //get the number from list item's id using regex
        var number = id.match(/\d/g);

        //showing div with id notContent_+number
        $('#notContent_'+number).show();

    });

});

Upvotes: 1

Related Questions