So maybe I'm just not looking in the right places but I can't find a good explanation of how to do the equivalent of jQuery's
$('a').click(function(){ // code here });
in plain old JavaScript?
Basically I want to run a function every time an a
tag is clicked but I don't have the ability to load jQuery into the page to do it in the way above so I need to know how to do it using plain JavaScript.
Vanilla JS helped the developers in creating dynamic websites. Then came jQuery, a library of tools created by developers around the world, using Javascript. In simple words, jQuery is a lightweight and easy to use JavaScript library that helps in creating complex functionalities with few lines of coding.
"VanillaJS is a name to refer to using plain JavaScript without any additional libraries like jQuery back in the days. People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries."
The equivalent to $() or jQuery() in JavaScript is querySelector() or querySelectorAll() , which, just like with jQuery, you can call with a CSS selector.
Vanilla JavaScript refers to using plain Javascript without any additional libraries or frameworks. The term became popular when Eric Wastl created the Vanilla JS site in 2012 as a joke. The site tries to bring attention to the fact that you can use just plain Javascript in many cases.
Working Example: http://jsfiddle.net/6ZNws/
Html
<a href="something">CLick Here</a> <a href="something">CLick Here</a> <a href="something">CLick Here</a>
Javascript:
var anchors = document.getElementsByTagName('a'); for(var z = 0; z < anchors.length; z++) { var elem = anchors[z]; elem.onclick = function() { alert("hello"); return false; }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With