Good afternoon, I'm trying to execute a function when loading the page, if I do it with addEventListener it returns null , but the same function with window. onload works perfectly.
Example with window.onload :
function saludar() {
document.querySelector('#elem').innerHTML = 'Hola piti';
}
window.onload = function () {
document.querySelector('#btn').onclick = saludar;
};
HTML Code:
<button id="btn">mostrar</button>
<div id="elem" ></div>
If you try it, it works perfectly, however now I'm going to do the same with the listener:
Example with addEventListener:
var target = document.querySelector('#btn');
target.addEventListener('click', saludar, false);
function saludar() {
document.querySelector('#elem').innerHTML = 'Hola piti';
}
You will see that in this last code it returns null.
What is the correct way to do it? to be able to be for ES6 and I would appreciate it to be only Javascript, nothing of Frameworks since in jQuery or others I know how to do it.
Greetings.