Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Setting onclick dynamically and passing in the element itself

I'm dynamically creating some <div> elements and then filling their innerHTML properties with text. I'm trying to set their onclick event handlers like this:

myDiv.onclick = function() { alert("Hello!") };

That I can do. What I would like to do is be able to access the value / innerHTML (new to Javascript and DOM, so I'm unsure of what term is what I'm looking for) within the newly defined onclick function. How would I go about accessing the data of myDiv within the function being defined for its onclick property? myDiv will be something simple like:

<div>StackOverflow</div>

Any help would be greatly appreciated!

like image 542
Nick Van Hoogenstyn Avatar asked Nov 18 '11 11:11

Nick Van Hoogenstyn


1 Answers

The onclick handler is executed in the context of the element.

myDiv.onclick = function () { alert(this.innerHTML); };
like image 188
J. K. Avatar answered Sep 28 '22 04:09

J. K.