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 trialYoussef Girgeis
iOS Development Techdegree Student 10,996 PointsHow to get the value of an element when it is clicked in javascript?
i have a list like this:
<ul>
<li><a>1</a></li>
<li><a>2</a></li>
<li><a>3</a></li>
<li><a>4</a></li>
</ul>
how to get the values between the a tags when i click on them?
2 Answers
Chyno Deluxe
16,936 PointsHey Youssef,
You can start by targeting the li tags.
var listItems = document.querySelectorAll("ul li"); // this returns an array of each li
then you can iterate through each item in the array
listItems.forEach(function(item) {
item.onclick = function(e) {
console.log(this.innerText); // this returns clicked li's value
}
});
Here is a visual (jsFiddle Demo)[https://jsfiddle.net/kt0cd6jg/2/]. I hope this helps.
Youssef Girgeis
iOS Development Techdegree Student 10,996 PointsHey Chyno, thanks so much. i really appreciate you help.