1

I have multiple html elements with same class name i want to know which element clicked in pure javascript

<a href="#" data-wow="1" class="wow">link a</a>
<a href="#" data-wow="2" class="wow">link a</a>
<a href="#" data-wow="3" class="wow">link a</a>

in javascript i tried a lot of solutions but all i found working with one element only

what i wrote so far

    var dd = document.getElementsByClassName('messages-email');

    dd.onclick() = function(ee){
      // if i clicked the first link i want to get data-wow which is 1
      // and if i clicked the third one i wanna get data-wow which is 3
      console.log('i want the clicked elemet attribute ')
    }

1 Answers1

8

There are a few issues with your code:

  1. There is no element with the class message-email in your markup. I suppose it's simply a mistake when you're attempting to demonstrate your markup, and that you are referring to the anchor elements with the wow class
  2. document.getElementsByClassName returns a Node collection. You will have to iterate through the collection in order to bind the click event. You can use Array.prototype.forEach.call(<NodeCollection>, function(element) { ... }) to iterate through your node collection
  3. Do not use .onclick to bind click event, as that will override any onclick handlers. You should be using .addEventListener('click', function() {...}) instead
  4. In order to access data-wow attribute, use the HTML5 dataset API

With that in mind, here is a proof-of-concept example:

var dd = document.getElementsByClassName('wow');

Array.prototype.forEach.call(dd, function(element) {
  element.addEventListener('click', function() {
    console.log('data-wow value is: ' + element.dataset.wow);
  });
});
<a href="#" data-wow="1" class="wow">link a</a>
<a href="#" data-wow="2" class="wow">link a</a>
<a href="#" data-wow="3" class="wow">link a</a>

Bonus: If you are familiar with ES2015 (aka ES6), there is an even easier way to do this:

const dd = document.getElementsByClassName('wow');

Array.from(dd).forEach(element => {
  element.addEventListener('click', () => {
    console.log('data-wow value is: ' + element.dataset.wow);
  });
});
<a href="#" data-wow="1" class="wow">link a</a>
<a href="#" data-wow="2" class="wow">link a</a>
<a href="#" data-wow="3" class="wow">link a</a>
Terry
  • 63,248
  • 15
  • 96
  • 118