3

Goal: get the data-element from the button that is been clicked.

My current code:

Array.from(document.getElementsByClassName('my_buttons_class')).forEach((button) => {
     button.addEventListener('click', (e)=>{
           e.preventDefault();
           /*
                Here i want to get the 'data-element' from the clicked button
                something like 
                e.target.attr('data-element');
           */
     })
});

The button element is something like this:

<button class="my_buttons_class" data-element="some json">My button text</button>

Current problem: the listener works fine, but the e.target is just the HTML text of that element, so i can't use .attr() on it

Also already tried e.target['data-element'] but it return undefined

3 Answers 3

5

.attr() is a jQuery method, In vanilla JavaScript you have to use getAttribute() to access the attribute:

e.target.getAttribute('data-element');

Array.from(document.getElementsByClassName('my_buttons_class')).forEach((button) => {
  button.addEventListener('click', (e)=>{
    e.preventDefault();
    console.log(e.target.getAttribute('data-element'));        
  });
});
<button class="my_buttons_class" data-element="some json">My button text</button>

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

1 Comment

Wonderful, was looking exactly for this, thank you! :)
2

The button variable refers to the button being iterated over, so to access the data-element attribute of that element, use:

button.dataset.element

or, with getAttribute:

button.getAttribute('data-element')

Elements do not automatically get their attributes assigned as properties of their Javascript references - that only works for a certain few attribute types, like id, class, and name, which is why e.target['data-element'] didn't work.

2 Comments

element should be "data-element"? but in js i can't use "-" in elements name
An attribute of data-SOMETHINGHERE can be accessed via <element>.dataset.SOMETHINGHERE. There's no need to use bracket notation - accessing the dataset is enough.
2

Try using getAttribute:

Array.from(document.getElementsByClassName('my_buttons_class')).forEach((button) => {
     button.addEventListener('click', (e)=>{
           e.preventDefault();
           console.log(e.target.getAttribute('data-element'));
     })
});
<button class="my_buttons_class" data-element="some json">My button text</button>

Comments

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.