0

I am trying to add events dynamically to each element in my html, using data-* I get all elements and using forEach to iterate. But when I trigger events in any button, it returns in page the undefined value, it looks like it's lost the reference from this inside function, I really don't know what happened. Is the best approach to add events dynamically?

https://jsfiddle.net/tmmdsgoq/1/

<button data-event data-text="Button 1">Button 1</button>
<button data-event data-text="Button 2">Button 2</button>
<button data-event data-text="Button 3">Button 3</button>

<div id="container">

</div>

<script>
function init(){
 var elements = document.querySelectorAll("[data-event]");  
 elements.forEach(function(el){
  el.addEventListener("click", function(){
   document.querySelector("#container").innerHTML += this.text;
  });
 });
}

init();

</script>
1
  • You've asked a lot of questions and never marked any as correct? Theres a green tick next to all answers that you are meant to select to help others. Heres a helpful link for you stackoverflow.com/help/someone-answers Commented Aug 9, 2016 at 1:03

3 Answers 3

1
  1. Use textContent property instead of text, thus eliminating the need for data-text.
    Only several types of HTML elements support text property according to HTML5 specification: <title>, <a>, <option>, <script>, <body>.
  2. Beware document.querySelectorAll result may not have forEach method in older browsers.
  3. Use devtools (F12 key) debugger to inspect the values by setting a breakpoint inside the loop.
Sign up to request clarification or add additional context in comments.

Comments

0

To grab a value stored in a data-* property you need to access the dataset of the html element.

So your code would change from:

document.querySelector("#container").innerHTML += this.text;

To:

document.querySelector("#container").innerHTML += this.dataset.text;

Also, I would not use the data element as a selector--it is not their purpose --but rather a class element.

Your code is:

<button data-event data-text="Button 1">Button 1</button>
...
var elements = document.querySelectorAll("[data-event]");

And should be:

<button class="className" data-text="Button 1">Button 1</button>
...
var elements = document.getElementsByClassName("className");

Final Consideration, try out JQuery, it will make your life easier and your code nicer :)

Comments

0

The text property you're trying to access doesn't exist. You simply need to change this.text to this.getAttribute("data-text").

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.