Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get innerHTML of this element in javascript?

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?

like image 606
David Avatar asked Oct 06 '11 12:10

David


People also ask

How do I get the innerHTML element?

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.

What is the innerHTML property in Javascript?

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.

What is document getElementById () innerHTML in Javascript?

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.

What are getElementById () and innerHTML properties?

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.


2 Answers

<element onClick="alert(this.innerHTML);"> ... </element>
like image 150
Niet the Dark Absol Avatar answered Sep 27 '22 02:09

Niet the Dark Absol


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.

like image 43
davin Avatar answered Sep 26 '22 02:09

davin