Search code examples
javascripthtmlgreasemonkeyuserscriptstampermonkey

Unable to define a click event on a href tag


I am trying to write a click event for an anchor tag in my tampermonkey script.

var contentTag = document.getElementsByTagName("pre")[0];
var fileContents = contentTag.innerHTML;

contentTag.innerHTML = "";

var lines = fileContents.split("\n");
window.alert("Number of lines:"+lines.length);


for(var i=0; i<20; i++) {
if(i!==15)
 contentTag.innerHTML+=(lines[i]+"<br>");
else {
    contentTag.innerHTML+=("<a id=link1>Click me</a>");
    var link = document.getElementById('link1');
    link.addEventListener("click", function() {
        window.alert('I am clicked');
    }, false);
}
}

The alert message never gets triggered when I click on the link in the page dispalyed, even though I have a a click event listener defined. What am I doing wrong here?


Solution

  • It's the way you're adding HTML, you're reappending the link when you do this in the next iteration.

    link.innerHTML += something
    

    So the event handler is lost, and you can actually prove that by adding the event handler to the last element instead.
    If you do it the proper way, creating elements and appending them, it works fine

    var contentTag = document.getElementsByTagName("pre")[0];
    var fileContents = contentTag.innerHTML;
    
    contentTag.innerHTML = "";
    var lines = fileContents.split("\n");
    
    for (var i = 0; i < 20; i++) {
        if (i !== 15) {
            var txt = document.createTextNode(lines[i] || ''),
                br  = document.createElement('br');
            contentTag.appendChild(txt);
            contentTag.appendChild(br);
        } else {
            var link = document.createElement('a');
            link.id = 'link1';
            link.innerHTML = 'Click me';
            link.addEventListener("click", function () {
                alert('clicked')
            }, false);
    
            contentTag.appendChild(link)
    
        }
    }
    

    FIDDLE