lucky
lucky

Reputation: 27

How to get the text of li without giving them ids?

I have four li tags inside a ul tag.

i want to get text inside li tag when i select one li and i want to hide the other three li values.

Only the selected one should still be shown on the page.

<ul id="names">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
</ul>

Upvotes: 1

Views: 86

Answers (4)

dsgriffin
dsgriffin

Reputation: 68566

This answers both parts of your question:

$('#names li').click(function(){    
  var x = $(this).text(); // gets the text of the selected li
  alert(x); // displays the text inside the selected li 
  $(this).siblings().hide();​​​​ // hides all other li's   
});

Here is a working jsFiddle for your example.

Upvotes: 2

GautamD31
GautamD31

Reputation: 28763

Try like this

$("#names li").click(function(){
   var selected = $(this);
   alert('You have selected '+ $(this).text());
   $("#names li").hide();
   $(this).show();
});

check the fiddle DEMO

Upvotes: 0

tpbowden
tpbowden

Reputation: 2090

How about this? It will hide them all and display the one which was clicked using a jQuery selector.

$('#names li').click(function() {
    $('#names li').hide();
    $(this).show();
})

Example of use: http://jsfiddle.net/eqUD3/

Upvotes: 1

Bill
Bill

Reputation: 3517

$('#names li').click(function(){
    $(this).siblings().hide();
});

Upvotes: 3

Related Questions