Skip to content Skip to sidebar Skip to footer

Use Addeventlistener To Replace Each Onclick

I have unordered lists below for fruits, animals, trees....about 100 buttons with same class:

Solution 1:

Yes, you can do it :

var bbs = document.getElementsByClassName("bb");
for(var i =0; i< bbs.length; i++){
  bbs[i].addEventListener('click', function(){
    var attr = this.value;
    console.log(attr);
  });
}
<ul><li><buttonclass="bb"value="apple" >Apple</button></li><li><buttonclass="bb"value="banana">Banana</button></li><li><buttonclass="bb"value="cherry">Cherry</button></li></ul>

Instead of console.log(attr); you can call your custom function

Solution 2:

try that :

window.addEventListener( 'load' , function () {

    var list = document.querySelectorAll( 'ul > li > button' );

    for ( var i = 0 , l = list.length ; i < l ; i++ ) {

        list[ i ].addEventListener( 'click' , function () {
            aJax( this.value );
        } );

    }

} );

Solution 3:

the simplest way (no loops needed)

var container = document.querySelector("ul");
container.addEventListener("click", doSomething, false);
 
functiondoSomething(e) {
    if (e.target !== e.currentTarget) {
        var clickedItem = e.target.value;
        console.log(clickedItem);
    }
    e.stopPropagation();
}
<ul><li><buttonclass="bb"value="apple" >Apple</button></li><li><buttonclass="bb"value="banana">Banana</button></li><li><buttonclass="bb"value="cherry">Cherry</button></li></ul>

check this awesome article, I'm pretty sure it's what you're looking for Handling Events for Many Elements

Solution 4:

While other answers are right, if your list is long, you might delegate the click to the ul element :

functionlogValue(evt){
  let target = evt.target;
  // only console.log if the click target has class "bb"if(target.classList.contains("bb")){
    console.log(target.value)
  }
}

// wait for the document to be loadedwindow.addEventListener("load",()=>{
  let list = document.querySelector(".my-list");
  if(list){
    //delegate click handler to the <ul> element
    list.addEventListener("click", logValue);
  }
});
<ulclass="my-list"><li><buttonclass="bb"value="apple">Apple</button></li><li>Banana
    <ul><li><buttonclass="bb"value="green_banana">Green_banana</button></li><li><buttonclass="bb"value="yellow_banana">Yellow Banana</button></li></ul></li><li><buttonclass="bb"value="cherry">Cherry</button></li></ul>

Post a Comment for "Use Addeventlistener To Replace Each Onclick"