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.
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.
Solution 2 :
The main problem is that you are using JavaScript inline with your HTML and this is not being bound to hyperlink as you expect.
document.querySelector("a").addEventListener("click", function() {
// Don't use .innerHTML when there is no HTML
// Use .textContent instead
test(this.textContent);
});
function test(content){
console.log(content);
}
<a href="#">cats</a>
But, better still, don’t use hyperlinks as triggers for JavaScript. Just about any visible (and some invisible) elements can be clicked on and trigger a click event. Hyperlinks are for navigation and people that rely on screen readers will have issues if hyperlinks are used for other purposes. Instead, another inline element, like a span should be used:
document.querySelector("span").addEventListener("click", function() {
// Don't use .innerHTML when there is no HTML
// Use .textContent instead
test(this.textContent);
});
function test(content){
console.log(content);
}
<span>cats</span>
Problem :
I would like to send the text between an pair as a parameter to a javascript function.
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.
Comments
Comment posted by Alan C.
This was perfect! Thank you. And for the explanation. It works beautifully. 🙂 I will look into the “best practices” changes too. Again thank you!
Comment posted by Alan C.
Thank you. I will look into incorporating this strategy in the code.