Search code examples
javascriptthisinnerhtml

Sending inner text of <a></a> tags as a parameter to a javascript function


I would like to send the text between an pair as a parameter to a javascript function.

Im trying this:

<a href="javascript: insertTag(this.innerHTML);">cats</a>

The function insertTag() is called, but the parameter sent looks to be "undefined" when I access it within the insertTag() function.

What am I doing wrong and how can I send what's between the tags as a parameter for my "insertTag" function (eg. "cats" in the example shown above?

Assigning the an id and then using GetElementById(id).innerhtml works, but I feel like there might be a simpler way without having to assign "ids" to each pair that calls the function.

Help is much appreciated.


Solution

  • Contrary to how onclick, onchange, and any other on attributes work, the href attribute used with javascript: will not set this to the HTML element the attribute is defined on. So it will be set the global object window, which does not have an innerHTML property.

    To make your use case work, do this:

    <a href="javascript: null" onclick="insertTag(this.innerHTML);">cats</a>
    

    Now the href attribute defines no specific action (null does nothing), but is still there to make the a element render as a hyperlink. The real action is now dealt with in the onclick attribute, where this will be what you expected.

    A remark

    Most will consider it better practice to define click handlers in separate JavaScript code, like this:

    document.querySelector('#mylink').addEventListener("click", function () {
        insertTag(this.innerHTML);
    });
    

    And your element would be:

    <a href="javascript: null" id="mylink">cats</a>
    

    This has the advantage that the on-click handler code is parsed when the script loads, not when the user clicks. So any syntax errors would immediately be reported.