最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - toggle class on click with javascript - Stack Overflow

programmeradmin0浏览0评论

I am trying to create a simple on click event using js (no jQuery) If I run the below code it only works for the first item I click.

    var listItem = document.querySelector('li');
    listItem.addEventListener('click', function(event) {
      this.classList.toggle('clicked');
    });
.clicked {
  color:red;
}
<ul id="mylist">
  <li>item 1</li>
  <li>item 2</li>
</ul>

I am trying to create a simple on click event using js (no jQuery) If I run the below code it only works for the first item I click.

    var listItem = document.querySelector('li');
    listItem.addEventListener('click', function(event) {
      this.classList.toggle('clicked');
    });
.clicked {
  color:red;
}
<ul id="mylist">
  <li>item 1</li>
  <li>item 2</li>
</ul>

I looked at an alternative using

        var listItem = document.getElementById('mylist');
        listItem.addEventListener('click', function(event) {
          this.classList.toggle('clicked');
        });
    .clicked {
      background-color:red;
    }
        <ul id="mylist">
          <li>item 1</li>
          <li>item 2</li>
        </ul>
but this just toggles the ul rather than the li I clicked.

How can I target all li in my list so that each time they are clicked their class is toggeled

Share Improve this question asked Sep 28, 2014 at 12:29 ak85ak85 4,26420 gold badges71 silver badges114 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You should use querySelectorAll instead of querySelector, then loop over all list items:

var listItems = document.querySelectorAll('li');
for(var i = 0; i < listItems.length; i++){
    listItems[i].addEventListener('click', function(event) {
      this.classList.toggle('clicked');
    });
}
发布评论

评论列表(0)

  1. 暂无评论