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?
Setting the innerHTML property of an element To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.
The innerHTML property returns: The text content of the element, including all spacing and inner HTML tags. The innerText property returns: Just the text content of the element and all its children, without CSS hidden text spacing and tags, except <script> and <style> elements.
The easiest way to modify the content of an HTML element is by using the innerHTML property. To change the content of an HTML element, use this syntax: document.getElementById(id).innerHTML = new HTML.
innerHTML = 'Data or content'; getElementById: The getElementById refers to the HTML element using its ID. Data or content: Data is the new content to go into the element.
<element onClick="alert(this.innerHTML);"> ... </element>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With