Binding an event listener to multiple elements with the same class

后端 未结 3 1063
臣服心动
臣服心动 2020-12-20 07:30

I\'m trying to apply the onclick event with JavaScript to the following elements:

first
3条回答
  •  被撕碎了的回忆
    2020-12-20 08:06

    To expand on the solution provided by @rock star I added two small additions to the function. First it is better to add / reemove a class (with an associated style rule) to an element than directly applying the stylerule to the element.

    Secondly - on the click event - this will now remove the red class (and therefore style) from the previously selected element and add it to the new element. This will allow only one element to be red at a time (in the original solution any element that was clicked would become red).

    var els = document.getElementsByClassName('abc');
    for (var i = 0; i < els.length; i++) {
      els[i].onclick = fun1;
    }
    
    function fun1() {
      var oldLink = document.getElementsByClassName('red')[0];
      if(oldLink) {oldLink.classList.remove('red')};
      this.classList.add('red');
    }
    .red {
     color:red;
    }
    first
    second
    third

提交回复
热议问题