简体   繁体   中英

Looping through a HTML list with JavaScript

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?

$("ul > li").on("click", function(e){
   console.log(this.textContent);
});

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

  • $('ul > li') creates an array of jQuery object made of all the li s
  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM