Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  8] [ 4]  / answers: 1 / hits: 23269  / 9 Years ago, fri, august 7, 2015, 12:00:00

I have a 'div' element generated in javascript with 'innerHTML' property.



(...).innerHTML = 'sometext'+'<div id=a>word</div>'+obj.something+'othertext';


Anyway onclick event is not working.



document.getElementById('a').onclick = function() {
//do something
}


What is the problem? How do I resolve it (pure javascript, no libraries)?


More From » click

 Answers
20

You could delegate the event listening to the parent to which you are innerHTML-ing the div , in yout code indicated by (...).
This would handle the events fired in the (...) and you can perform actions conditioned to event.target.id === 'a'



(...).onclick = function(event) {
if (event.target.id === 'a') {
//Do your stuff
}
}


This way you not need to worry about if, when you attach the listener, you have already created the div dinamically or not.
Also, to register the event handler, I suggest proper event handle registering (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)


[#65498] Wednesday, August 5, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shane

Total Points: 239
Total Questions: 91
Total Answers: 114

Location: Faroe Islands
Member since Tue, Jul 7, 2020
4 Years ago
shane questions
;