AddEventListener after appendChild

I am creating an element eltTooltip, s document.createElement, etc. and add it to the DOM like this ( idTooltipcontains idof eltTooltip):

document.body.appendChild(eltTooltip);
var addedElt = document.getElementById(idTooltip);
addedElt.addEventListener("click", function(){...});

Is the event clickguaranteed to be added here, or maybe the DOM is not ready for it?

Can I do it better? (The page has been loaded for a long time, so window.onloadit cannot be used. And I cannot use jQuery here.)

+4
source share
2 answers

Your method works fine, but it might be better to attach an event listener before adding it to the DOM with eltTooltip. This will save you the choice of an element from the DOM.

Demo

var idTooltip = 'test';
var eltTooltip = document.createElement('div');
eltTooltip.innerHTML = "test"
eltTooltip.setAttribute('id', idTooltip);
eltTooltip.addEventListener("click", function () {
    alert('click');
});

document.body.appendChild(eltTooltip);
+5
source

-

window.onload = function (){
    var toolTip = document.createElement('div');
    toolTip.innerHTML = "someData";
    toolTip.addEventListener('click', myfunction);
    document.body.appendChild(toolTip);

    function myfunction(){
        alert("hello guys ");
    }
}
+1

All Articles