lenden
lenden

Reputation: 830

Event listener doesn't work when I add something to div.innerHTML

this is my code :

<html>
<head>
    <script type="text/javascript" language="javascript">
        function load() {
            div1 = document.getElementById('div1');
            div2 = document.getElementById('div2');
            function clicky() {
                alert('1');
            }
            div2.addEventListener('click', clicky);
            //div1.innerHTML += 'ooooooofdsfdsfdsfdsfdsfsdfdsfdsfdsfdsklfdsjfkldsjfkldsjfldsjfkldsjfkldsjfdskl';
        }       
    </script>
</head>
<body onload="load();">
    <div id="div1" style="width : 300px; height : 300px; background-color : red; position : absolute">

        <div id="div2" style="width : 20px; height : 20px; background-color : green; position : absolute; right : 5px; top : 5px;">X</div>

    </div>
</body>

So, I have div2 in div1. If commented string is really commented, everything works : clicking on div2 causes alert. But if I add smth to div1.innerHTML, event handler doesn't work. Where is the problem?

Upvotes: 0

Views: 453

Answers (1)

Parthik Gosar
Parthik Gosar

Reputation: 11646

Your code

div1.innerHTML += 'ooooooofdsfdsfdsfdsfdsfsdfdsfdsfdsfdsklfdsjfkldsjfkldsjfldsjfkldsjfkldsjfdskl';

actually means

div1.innerHTML = div1.innerHTML + ooooooofdsfdsfdsfdsfdsfsdfdsfdsfdsfdsklfdsjfkldsjfkldsjfldsjfkldsjfkldsjfdskl';

So in literal sense, you are overwriting the innerHTML of div1 with a new string which inturn creates a new object of div2. Hence you need to add click listener after the innerHTML is set.

Upvotes: 1

Related Questions