Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

click event on innerHTML generated div

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)?


1 Answers

You need to bind that id with the function after you added the the innerhtml to the outer html

function bindingFunction(){
    document.getElementById('a').onclick = function() {
//     Your code
    }
}

Just after adding the innerHTML

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

This will work.

like image 121
Harshit Gupta Avatar answered Mar 19 '26 15:03

Harshit Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!