14

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!

1
  • 1
    "Contents" is the correct term I think. Commented Nov 18, 2011 at 11:33

3 Answers 3

23

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

myDiv.onclick = function () { alert(this.innerHTML); };
Sign up to request clarification or add additional context in comments.

1 Comment

Doh! This must have been the only thing I didn't try. Thanks a lot!
4

Inside the handler, this will refer to the element.

myDiv.onclick = function() { alert(this.innerHTML) };

Tadaaa :).

Comments

0

I think what you're after is:

myDiv.onclick = function () { 
    alert(this.innerHTML); 
    };

Personally I'd stay away from innerText (due to browser issues) and use innerHTML as a rule

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.