I'm trying to add an event click
but it doesn't work for me, it tells me it's not possible addEventListener
to a null property, but the name of the button is the same as the one I'm adding the event to.
If from the button I place onclick="saludar()"
there if it is executed and, as I see comments, the script is located before closing the body
but it does not work for me it does not recognize it but only with adding event, because that usually happens, because it is the same id From the name that I place in the selector I have something like this:
A button with id=boton_r
and in js I do this
let bot=document.getElementById("boton_r"; bot.addEventListener("click",function (){
Alert("HOLA");
})
but it doesn't work for me with add
and onclick
from html
itself, and the strange thing is that if I create a new project with a single file html
and before closing body
I make the script and add the event if it works. Do you know what I could do in this case?
This happens because the DOM is not yet loaded, the event that you are assigning to an element of your DOM does not exist yet and that is why it does not contain that event.
You can use jquery
$(document).ready()
or if you are doing it with pure JS you can use domready.js