0

I have a function in a javascript file that adds a link to a paragraph that I created in the HTML file. I want to call a function that is defined in the javascript file when the user clicks the link.

My HTML:

<p id="para"></p>

My JavaScript:

var paraHTML = document.getElementById("para");

function addLink(id) {
    paraHTML.innerHTML += '<a id="' + id + '" onclick="clickedTest(); return false;">Click me!</a>'
}

function clickedTest() {
    console.log('here');
}

I have also tried using href e.g.

paraHTML.innerHTML += '<a id="' + id + '" href="javascricpt:clickedTest();">Click me!</a>'

But both ways give me an error saying: ReferenceError: clickedTest is not defined

I have tried using the following code from this question but the number of links is constantly changing whilst my code is running which makes it difficult to use:

var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
    elements[i].onclick = function () {
        console.log('here')
    }
}

The addLink() function is called elsewhere in my javascript program several times

4
  • You can use onClick() directly inside para, <p onclick="addLink()"></p> Commented Jan 30, 2019 at 10:32
  • What is the scope of the clickedTest() function? Do you have it inside a load handler? Since your code is working as expected. Make sure the function is in the global scope. Commented Jan 30, 2019 at 10:32
  • its working fine for me bro Commented Jan 30, 2019 at 10:35
  • 1
    You can also try document.getElementById(id).addEventListener("click", clickedTest); after adding the element. Commented Jan 30, 2019 at 10:39

2 Answers 2

4

Using innerHTML to create content is usually slow and is usually discouraged, a more organic approach will be to create the element pragmatically and then adding event listener to that element. For example,

var elem = document.createElement('a');
elem.addEventListener('click', myClickHandler);
elem.innerText = 'My Tag';
paraHTML.appendChild(elem)

function myClickHandler(e) {
  console.log('a is clicked')
}

This will not only fix your problem but will make your code more manageable

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, I had noticed my program had been running very slowly
Good answer but documeent should be document ;)
Good work. Also better to keep using ; on all lines or none of them.
0

You can do something like this:

function callMe(){
}
var newLink = document.createElement('a');
newLink.href="javascript:callMe();";
newLink.innerHTML="this is a link";

paraHTML.appendChild(newLink);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.