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

12,569

Solution 1

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();

Solution 2

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

Solution 3

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

$("#pressed").click(function() {
   alert($('#list .two').text());
});
Share:
12,569
John 'Mark' Smith
Author by

John 'Mark' Smith

I have come to ask questions.

Updated on June 05, 2022

Comments

  • John 'Mark' Smith
    John 'Mark' Smith almost 2 years

    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.

  • alexpls
    alexpls over 10 years
    For really proper HTML you should also use either an anchor tag (<a href="#" id="pressed">Submit</a>) or a button tag (<button id="pressed">Submit</button>) for anything that's clickable.
  • Paulie_D
    Paulie_D over 10 years
    @max_w Source please...although I don't necessarily disagree.
  • Rory McCrossan
    Rory McCrossan over 10 years
    @max_w from an accessibilty point I agree. However there are certain cases where that is just not possible.
  • alexpls
    alexpls over 10 years
    Sorry, I made a generalisation in my statement. Most times (and most certainly in the case of the example in this question) an anchor tag or a button should be used for clickable elements. The benefits of using them include getting cursor: pointer by default, getting the tabindex on the element set by default, and identifying the tags as clickable with screen readers. I do agree that sometimes they aren't he best fit though (like when you're trying to make a block element which contains nested elements clickable).
  • Rory McCrossan
    Rory McCrossan over 10 years
    @max_w completely agree