Control HTML DOM with Javascript without inserting calling functions in tags [duplicate]

  • A+
Category:Languages

This question already has an answer here:

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> 


You can use addEventListener on your p tag.

getElementsByTagName('p')[0] will return array of p tags, in your case you need add listener to single paragraph (its index 0, thats why we have [0])

<!DOCTYPE html> <html> <body> <p>Click on this paragraph</p> <script>   document.getElementsByTagName("p")[0].addEventListener("click", function() {     alert('The paragraph was clicked.')   }); </script> </body> </html>

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: