0

I'm writing a chrome extension, and I'm trying to add a link that calls a javascript function, exactly like in the question.

However, when I click the link, nothing happens - and when I look at the debug console, the "a" node doesn't have an "onclick" property at all, it just looks like this:

<a href="#">Add to likes</a>

This is my code:

function generateEntry(innerEntry) {    
    var a = document.createElement('a');
    var linkText = document.createTextNode("Add to likes");
    a.appendChild(linkText);
    a.onclick="addToLikes('" + "hello" + "')"
    a.href = "#";
    return a
}

If I manually add the "onclick" declaration in the debug console, everything works.

<a href="#" onclick="addToLikes('hello2')">Add to my likes</a>

What's wrong with my script?

Community
  • 1
  • 1
Yossale
  • 14,165
  • 22
  • 82
  • 109

2 Answers2

0

you have to use the function for onclick

function generateEntry(innerEntry) {    
    var a = document.createElement('a');
    var linkText = document.createTextNode("Add to likes");
    a.appendChild(linkText);
    //a.onClick="addToLikes('" + "hello" + "')"
    a.onclick = function () {
    addToLikes('hello2');
    };
    a.href = "#";
    return a
}
Yossale
  • 14,165
  • 22
  • 82
  • 109
Mirko Cianfarani
  • 2,023
  • 1
  • 23
  • 39
0

The onclick property takes a function as its value, not a string.

function addHelloToLikes() {
    addToLikes("hello");
}

a.onclick = addHelloToLikes;

You may wish to use, the more modern, addEventListener method instead.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335