Alpha2k
Alpha2k

Reputation: 2241

JavaScript create element then add it an event

I am trying to create an element (without DOM or jQ pls) and then apply it an even... The new created element displays properly and javascript works...

var dato = "";
    dato += "<div id='todas'>";
    dato += "<img src=/logos/todos_generos.jpg>";
    dato += "<span>Todas</span>";
    dato += "</div>";

    document.getElementById('generos').innerHTML += dato;
    document.getElementById("todas").onclick = myFunction;


function myFunction(){
alert("This is not working");
}

But if later on i add another element using innerHTML also, the previous elements JS would stop working:

var dato = "";
    dato += "<div id='someRandom'>";
    dato += "<img src=/logos/todos_generos.jpg>";
    dato += "<span>Todas</span>";
    dato += "</div>";

    document.getElementById('generos').innerHTML += dato;
    document.getElementById("todas").onclick = myFunction;

Ive heard innerHTML gives problems on elements already created, this should be done by appending childs but thats just too large to manage properly.

Upvotes: 1

Views: 77

Answers (2)

dfsq
dfsq

Reputation: 193301

Don't use innerHTML, it removes all event handlers previously bound to elements. You can use insertAdjacentHTML method which will preserve events:

var dato = "";
    dato += "<div id='someRandom'>";
    dato += "<img src=/logos/todos_generos.jpg>";
    dato += "<span>Todas</span>";
    dato += "</div>";

document.getElementById('generos').insertAdjacentHTML('beforeend', dato);

Another solution is to manually append new elements using appendChild method but this is more verbose:

var div = document.createElement('div');
div.innerHTML = dato;
document.getElementById('generos').appendChild(div);

Upvotes: 1

Sirko
Sirko

Reputation: 74106

You could insertAdjacentHTML(), which works similar, but does not disrupt the existing elements:

document.getElementById('generos').insertAdjacentHTML( 'beforeend', dato );

The way innerHTML works is basically:

  • get all HTML content as a string
  • append your new string
  • write the result back as content to the element

When converting the existing elements back to text, you obviously lose all assigned event handlers.

Upvotes: 1

Related Questions