DelphiStudent
DelphiStudent

Reputation: 394

how do i set onclick event within innerHTML?

i am trying to use innerHTML to insert some data into an html page like folowing

for(i = 0; i < data.length; i++){
var line = data[i].split("~");

nameslist.innerHTML += '<p onClick='+userclick(line[1])+'><strong>' + line[0] + ' </strong></p>';

}

but onclick event fired automatically directly after the insert and it wont fire when i click on the <p> element

how do i use innerhtml properly to add a p element with onclick event and fire it only when user click ?

Upvotes: 3

Views: 2568

Answers (1)

user11162572
user11162572

Reputation:

If you are willing to take a different approach you could add an event listener to a parent node and let the click event bubble up to the parent.

An example can be found here: https://davidwalsh.name/event-delegate

// Get the element, add a click listener...
document.getElementById("parent-list").addEventListener("click", function(e) {
    // e.target is the clicked element!
    // If it was a list item
    if(e.target && e.target.nodeName == "LI") {
        // List item found!  Output the ID!
        console.log("List item ", e.target.id.replace("post-", ""), " was clicked!");
    }
});

Upvotes: 5

Related Questions