jQuery - get <li> from <ul> with a specific class

I have a list:

<ul id="list">
   <li class="one">Item A</li>
   <li class="one">Item B</li>
   <li class="two">Item C</li>
   <div id="pressed">Submit</div>
</ul>

and when "Submit" is pressed I want to retrieve the value of the list item which has a class of "two". In this instance, pressed Submit would return "Item C". Here's the jQuery I've tried:

$("#pressed").click(function() {
   var v = $('#list').filter('.two').val();
   alert(v);
});

But all this returns is 0. What's the best way to do this? Only one <li> will have a class of "two" at any one time.

Upvotes: 2

Views: 12988

Answers (3)

Hossain Muctadir
Hossain Muctadir

Reputation: 3626

After Rory McCrossan's correction with HTML you can do this.

$("#pressed").click(function() {
   alert($('#list .two').text());
});

Upvotes: 1

Adil
Adil

Reputation: 148110

You need html() or text() instead of val(). The function val() is used for input elements like text, checkbox etc. Also put div outside ul to make your html valid as Rory McCrossan pointed

Live Demo

var v = $('#list').filter('.two').html();

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly, your HTML is invalid as div elements cannot be children of ul:

<ul id="list">
   <li class="one">Item A</li>
   <li class="one">Item B</li>
   <li class="two">Item C</li>
</ul>
<div id="pressed">Submit</div>

Secondly, text() is the property you want, not val():

$("#pressed").click(function() {
   var v = $('#list').find('.two').text();
   alert(v);
});

Example fiddle

Upvotes: 8

Related Questions