2

I use native js and I need get value from data-atribute all elements which I click on.

window.onload = function() {

    let btn = document.getElementsByClassName('btn');

    for( let i = 0; i < btn.length; i++ ) {
        btn[i].addEventListener( "click" , function(e) {
            let dataBtn = e.getAttribute('data-btn');
            console.log(dataBtn);
        });
    }

};

But I get error (e.getAttribute is not a function)

Have I can get and use this in native js?

radha
  • 11
  • 1
  • `e.target.getAttribute(...)` https://developer.mozilla.org/en-US/docs/Web/API/Event/target – Satpal Apr 27 '17 at 09:18
  • I prefer the dataSet object `e.target.dataSet.btn` – evolutionxbox Apr 27 '17 at 09:19
  • [Here](http://stackoverflow.com/questions/15912246/access-data-attribute-without-jquery) and [here](http://stackoverflow.com/questions/33760520/get-data-attributes-in-javascript-code) – evolutionxbox Apr 27 '17 at 09:21
  • @SankarRaj That is Jquery and not javascript solution – Suresh Atta Apr 27 '17 at 09:34
  • @Satpal I don't believe that is not a dupe since OP know how to reiceive event in callback. Actual dupes are here : 1) http://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event 2) http://stackoverflow.com/questions/14422898/how-to-get-an-elements-id-from-event-target – Suresh Atta Apr 27 '17 at 09:36

1 Answers1

2

You can access the 'data-btn' attribute of the current clicked element in the event handler function by calling this.getAttribute('data-btn') or also by calling btn[i].getAttribute('data-btn');.

Code:

let btn = document.getElementsByClassName('btn');

for (let i = 0, len = btn.length; i < len; i++) {
  btn[i].addEventListener('click' , function() {
    let dataBtn = this.getAttribute('data-btn');
    console.log(dataBtn);
  });
}
<a class="btn btn-default" data-btn="1" href="#" role="button">Link</a>
<button class="btn btn-default" data-btn="2" type="submit">Button</button>
<input class="btn btn-default" data-btn="3" type="button" value="Input">
<input class="btn btn-default" data-btn="4" type="submit" value="Submit">
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46