Alberto
Alberto

Reputation: 12899

Get an attribute from the clicked element with Javascript

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

Upvotes: 3

Views: 8070

Answers (3)

Mamun
Mamun

Reputation: 68933

.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>

Upvotes: 5

Blue
Blue

Reputation: 22911

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>

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370669

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.

Upvotes: 2

Related Questions