Get text and id from an li element on click with pure JS

前端 未结 2 1997
逝去的感伤
逝去的感伤 2021-01-28 22:12

I\'ve been stuck with this for several days and I can\'t solve it.

I\'ve done it with jQuery with no problem, but I need it in pure JS.

This is how my list is ge

2条回答
  •  长情又很酷
    2021-01-28 23:01

    you haven't specified whether this is for a specific list or just any li on your page. The below will log the id and innerHTML components of any li on the page. Perhaps you may need to update the querySelector for your particular use case.

    var list = document.querySelectorAll('li');
    
    Array.prototype.slice.call(list).forEach(function(listItem){
      listItem.addEventListener('click', function(e){
        console.log(this.id);
        console.log(this.innerHTML);
      });
    });
    

    Here's a JSFiddle which I think demonstrates what you are trying to achieve.

提交回复
热议问题