1

How do I loop through a list of li tags inside a ul in order to get the textContent of the clicked li element?

var ul    = document.getElementsByClassName('ul')[0];
var items = ul.getElementsByTagName('li');

$("li").on("click", function(){
    for (var i =0; i<items.length;i++) {
        console.log(items[i]);
    }
});

My attempt above logs the textContent of all the li elements within the list whereas I only want the textContent of the clicked element. How could I specify the element clicked?

1
  • 3
    $("li").on("click", function(){console.log($(this).text());}); Commented Jun 27, 2017 at 17:46

2 Answers 2

3
$("ul > li").on("click", function(e){
   console.log(this.textContent);
});
Sign up to request clarification or add additional context in comments.

Comments

0

Kiluminati's answer should do the trick. This is how it works:

  • $('ul > li') creates an array of jQuery object made of all the lis
  • The jQuery method .on() attaches an eventListener to the DOM object, in this case, each li element
  • When the element is clicked, the eventListener is triggered, and calls the handler function, binding its this variable context to the element that was clicked

1 Comment

Brilliantly explained, Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.