3

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 ?

10
  • You are calling the function, not assigning the content to the attribute. Just put it within the string. '<p onClick="userclick(line[1])"> Commented Jun 20, 2019 at 14:42
  • Don't!. Mashing together strings to generate JS embedded in HTML inside a JS program is a nightmark. Use DOM methods like createElement, appendChild and addEventListener instead. It's more verbose but much easier to maintain. Commented Jun 20, 2019 at 14:43
  • I think this will depend on what flavor of ES you need to be using in terms of using template strings or arrow functions. You can always use setAttribute afterward. developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute Commented Jun 20, 2019 at 14:44
  • 1
    <p> elements aren't designed to be interactive. You can add a click event handler to them, but then someone comes along and can't use a mouse but they can't focus the <p> because it isn't designed to be a UI control. Use appropriate elements (e.g. <button>). Commented Jun 20, 2019 at 14:44
  • ooh that's a good point @Quentin Commented Jun 20, 2019 at 14:45

1 Answer 1

5

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!");
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

i accept this answer sense its refer to using event listener as @Quentin commented out

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.