5

Pretty simple question. I have an element (a tag) which has an onclick to call a javascript function. Amoung other things, I want this function to echo the innerHTML of the element that called it. So, in this case, the innerHTML of the atag.

How do I do this?

2 Answers 2

11
<element onClick="alert(this.innerHTML);"> ... </element>
Sign up to request clarification or add additional context in comments.

5 Comments

Nice try, but It kind of dismisses the fact that I said call a javascript function
"It works" isn't enough. The reason that went out of fashion is because it is poor practise.
this.innerHTML is the important part, so it's a valid answer.
+1 Nothing wrong with inline handlers. They can be very useful, and solve or simplify some problems.
+1 for an excellently efficient suggestion that doesn't require you to build a function outside of the element to call to reference back to the element itself to handle its own content
3

markup:

<element id="foo"> ... </element>

js:

document.getElementById('foo').addEventListener('click', fn);

function fn(){ alert(this.innerHTML); }

http://jsfiddle.net/g7Bau/2/

The important thing to note here, which essentially answers your question, is that the event listener when called has binds this to the DOM node that caused the event to fire. So we can use this in the function and it's generic. You could add another element, and bind a click listener also using fn and the one function would work for both elements.

1 Comment

@Raynos, you're right. The trend in all major browsers is to make it optional though, as per the HTML5 spec. This clearly isn't a cross-browser solution, since <IE9 this won't even work...

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.