Both codes below do the same thing, first using Vanilla JS and second using JQuery. JQuery code do not have to insert anything inside html tags, while JS have to insert the caller "onclick="myFunction()"".
How could I modify the JS code so that I have no need to insert anything inside html tags, exactly like JQuery code does?
Vanilla JS Code:
<!DOCTYPE html>
<html>
<body>
<p onclick="myFunction()">Click on this paragraph</button>
<script>
function myFunction() {
alert("The paragraph was clicked.");
}
</script>
</body>
</html>
JQuery Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
alert("The paragraph was clicked.");
});
});
</script>
</head>
<body>
<p>Click on this paragraph.</p>
</body>
</html>
Array.from(document.querySelectorAll("p")).forEach(function(p) {p.addEventListener('click',myFunction);}); function myFunction(e) {alert('You clicked on '+this);}