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
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);
});
Solution 3
After Rory McCrossan's correction with HTML you can do this.
$("#pressed").click(function() {
alert($('#list .two').text());
});
Comments
-
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 over 10 yearsFor 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 over 10 years@max_w Source please...although I don't necessarily disagree.
-
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 over 10 yearsSorry, 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 thetabindex
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 over 10 years@max_w completely agree