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?

David
  • 16,246
  • 34
  • 103
  • 162

2 Answers2

11
<element onClick="alert(this.innerHTML);"> ... </element>
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Nice try, but It kind of dismisses the fact that I said call a javascript function – David Oct 06 '11 at 12:33
  • 1
    "It works" isn't enough. The reason that went out of fashion is because it is poor practise. – davin Oct 06 '11 at 12:37
  • 2
    `this.innerHTML` is the important part, so it's a valid answer. – Kelly Oct 06 '11 at 12:39
  • 3
    +1 Nothing wrong with inline handlers. They can be very useful, and solve or simplify some problems. – user113716 Oct 06 '11 at 13:22
  • +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 – KittenCodings Mar 30 '16 at 14:41
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.

davin
  • 44,863
  • 9
  • 78
  • 78
  • @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 – davin Oct 06 '11 at 13:11