Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Abdi Ahmed
7,151 PointsTraversing the DOM
Hi everyone
I would like to get the value of a li item within an ul with jquery:
<ul id=list"><li>Milk<button class="check">Check</button></li>
<li>Bread<button class="check">Check</button></li>
<li>Eggs<button class="check">Check</button></li></ul>
I tried:
$('.check').parent().val(); But this didn't work and returned 0 as the value. Basically I want to target the value of li item when the check button is clicked.
3 Answers
Ayoub AIT IKEN
12,314 Pointseuuh, not at all abide, if you actually do that :
$(".check").click(function() {
var string = $(this).parent().text();
});
it returns just the li text !!
Ayoub AIT IKEN
12,314 PointsHey Abdi !
I actually turned your code into this :
<ul id="list">
<li>Milk<input type="button" value="Check" class="check"></li>
<li>Bread<input type="button" value="Check" class="check"></li>
<li>Eggs<input type="button" value="Check" class="check></li>
</ul>
and javascript
var string = $(".check").parent("li").text();
and I got what you want !
Abdi Ahmed
7,151 Points@Ayoub thanks for the solution. It grabs the all of the contents inside the li element, but I go it to work with this:
($(this).parent().children("span").text());
Adding the span element allowed me to target the child of the li element only.
Thanks
Abdi Ahmed
7,151 PointsAbdi Ahmed
7,151 PointsMaybe if I changed the HTML to the way you did it - it might actually work with my event listener, but when I tested the code above it grabbed both milk and bread. Take a look here: http://jsfiddle.net/ut207o99/
Ayoub AIT IKEN
12,314 PointsAyoub AIT IKEN
12,314 PointsYeah its normal, cause i ve let you add my code to your click event handler, sorry i didnt precise it exactly.