1

My HTML has a some anchor tags with a data attribute as below:

<a href="#" class="color" data-colorValue="FF0000">Red</a>
<a href="#" class="color" data-colorValue="0000FF">Blue</a>
<a href="#" class="color" data-colorValue="00FF00">Green</a>

My JavaScript code needs to add a click event listener to each anchor tag. When the event is triggered, I need to get the color value. My code is below.

const colors = document.querySelectorAll('.color');

for(let i = 0; i < colors.length; i++){
  colors[i].addEventListener('click', () => {
    console.log('test to see if click is working');
    console.log(this.dataset.colorValue);
  });
}

I'm getting the error "Cannot read property 'colorValue' of undefined"

1
  • What is dataset? That's what's failing. The definition is not shown here. Commented Aug 23, 2019 at 16:01

2 Answers 2

2

use .getAttribute('data-colorValue');

const colors = document.querySelectorAll('.color').forEach(el => {
  el.addEventListener('click', e => {
    e.preventDefault();
    const color = el.getAttribute('data-colorValue');
    console.log(color);
  });
});
<a href="#" class="color" data-colorValue="FF0000">Red</a>
<a href="#" class="color" data-colorValue="0000FF">Blue</a>
<a href="#" class="color" data-colorValue="00FF00">Green</a>

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Exactly what I needed. Much obliged :-)
1

If you change your data attribute to data-color-value, you should be able to retrieve it using this.dataset.colorValue

See more about data attribute naming rules here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

The name of a custom data attribute in HTML begins with data-. It must contain only letters, numbers and the following characters: dash (-), dot (.), colon (:), underscore (_) -- but NOT any ASCII capital letters (A to Z).

1 Comment

Yes, I was able to retrieve the data attribute using the dataset.colorValue. Much obliged :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.