简体   繁体   中英

Javascript - How to get multiple data attribute of button when on click

I have multiple buttons with a data-rel attribute, how do I get that attribute on each button when they are clicked?

HTML

<button class="category" data-rel="all">All</button>
<button class="category" data-rel="banana">Banana</button>
<button class="category" data-rel="orange">Orange</button>
<button class="category" data-rel="watermelon">Watermelon</button>

JS

var btn = document.querySelector('.category');

btn.addEventListener('click', function() {
  var el = btn.getAttribute('data-rel');      
  alert(el);
})

I'm only able to get the attribute for the first button, but not the rest

 var btn = document.querySelector('.category'); btn.addEventListener('click', function() { var el = btn.getAttribute('data-rel'); alert(el); }) 
 .button { padding: 10px 20px; } 
 <button class="category" data-rel="all">All</button> <button class="category" data-rel="banana">Banana</button> <button class="category" data-rel="orange">Orange</button> <button class="category" data-rel="watermelon">Watermelon</button> 

I assume that you want a single function to handle every button. Therefore I declare the function outside of the loop, so it is declared only one time, and therefore saves memory. You are going to need this handle-function regardless of what version you use below to add the event listener.

// The handle function is declared outside the loop, saving memory.
// The current button is found in this
// Also using dataset to get the data.
function handle(event) {
  alert( this.dataset.rel );
}

To get all matching elements you need to use querySelectorAll . It returns a collection, and you can use the forEach -method to easily traverse the collection:

document.querySelectorAll('.category').forEach(
  function (btn) {
    btn.addEventListener('click', handle );
  }
);

This is the same type of call, but with modern arrow-function instead. I don't know what you prefer.

document.querySelectorAll('.category').forEach(
  btn => btn.addEventListener('click', handle )
);

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