I’ve seen that you can attach events like this
<button type="button" id="myButton" onclick="myFunction()">
can you do the same without the "onclick=", like:
document.getElementById('myButton'). //and here attach the event on click to myFunction
I’m trying to keep JavaScript and HTML separate.
It’s similar to the
onclickapproach, and in fact uses the same event-handler, but is removed from the HTML:If you don’t have an
idon the element you could also use:An alternative approach, using
Array.prototype.forEach(), with an array of elements created usingArray.prototype.slice()anddocument.querySelectorAll():This will execute the
yourFunctionName()function for each<input />element, oftype="text", returned bydocument.querySelectorAll()passing that<input />element into the function asthis.You could also use
addEventListener()in this case:And also in this situation, using
document.querySelector()(as opposed todocument.querySelectorAll()), which returns the first element that matches the passed-in selector, using CSS notation:Or:
References:
Array.prototype.forEach().Array.prototype.slice().document.querySelector().document.querySelectorAll().EventTarget.addEventListener().