your code is almost correct, but it does not work because you should not put it that way onClick
, since this way it will not work, instead you should write it like this onclick
, in lowercase, javascript
is sensitive to lowercase and capital letters, I'll give you an example:
function iniciar(){
document.getElementsByTagName('p')[0].onclick = saludar;
}
function saludar(){
alert('Hola!!');
}
//Ejecutamos 'iniciar()', como si fuera window.onload
iniciar();
<p>ejemplo 1er parrafo</p>
<p>ejemplo 3er parrafo</p>
<p>ejemplo 4to parrafo</p>
You can also use the addEventListener
method to 'add' a function to an event, like this:
function iniciar(){
document.getElementsByTagName('p')[0].addEventListener('click', saludar, false);
}
function saludar(){
alert('Hola!!');
}
iniciar();
<p>ejemplo 1er parrafo</p>
<p>ejemplo 3er parrafo</p>
<p>ejemplo 4to parrafo</p>
With regard to missing the parentheses, I commented that the parentheses make your function run, that is, if you do:
document.getElementsByTagName('p')[0].onclick = saludar();
You are executing the function saludar
and assigning the return of saludar
as function onclick
, but your function returns nothing, so the assignment would be something like .onclick = undefined;
, but you can also return a function so that is assigned to onclick
, I leave an example:
function iniciar(){
document.getElementsByTagName('p')[0].onclick = saludar();
}
function saludar(){
//Retornamos la función '_saludar'
return _saludar;
}
function _saludar(){
alert('Hola!!');
}
iniciar();
<p>ejemplo 1er parrafo</p>
<p>ejemplo 3er parrafo</p>
<p>ejemplo 4to parrafo</p>
I hope and it works, greetings.