How to get innerHTML of this element in javascript?
36,216
Solution 1
<element onClick="alert(this.innerHTML);"> ... </element>
Solution 2
markup:
<element id="foo"> ... </element>
js:
document.getElementById('foo').addEventListener('click', fn);
function fn(){ alert(this.innerHTML); }
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.
Author by
David
Updated on July 09, 2022Comments
-
David almost 2 years
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?
-
David over 12 yearsNice try, but It kind of dismisses the fact that I said call a javascript function
-
davin over 12 years"It works" isn't enough. The reason that went out of fashion is because it is poor practise.
-
Kelly over 12 years
this.innerHTML
is the important part, so it's a valid answer. -
davin over 12 years@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...
-
user113716 over 12 years+1 Nothing wrong with inline handlers. They can be very useful, and solve or simplify some problems.
-
KittenCodings about 8 years+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