1

I'm working in a little app, mostly using jquery, everything is working fine but I'd like to rewrite every jquery part with plain javascript to fully understand what I'm doing.

I've read this previus post, and everything makes perfect sense but I can't get any code to run in my browser.

How to select all <a> tag and register onclick event?

This is my code:

<html>
<head>
 <script type="text/javascript">
  var a = document.getElementsByTagName('a');
  var f = function () {alert('ok');}
  for (var i = a.length - 1; i >= 0; i--) {
   a[i].onClick = f;
  }

 </script>
</head>
<body>
<a href="#">test1</a>
<a href="#">test2</a>
</body>
</html>

In jquery I'd simply use this to find all anchors and run my function when clicked:

$('a').on('click',function (){
  alert('ok');
});

Any thoughts? thanks in advance, Gustavo

Community
  • 1
  • 1
gdc3000
  • 23
  • 2

2 Answers2

4

This is how I would do it:

var anchors = document.querySelectorAll("a"),
    i;

for (i=0; i<anchors.length; i+=1) {
    anchors[i].addEventListener("click", function() {
        alert("triggered!");
    });
}
<a href="#">test1</a>
<a href="#">test2</a>
s4nji
  • 449
  • 1
  • 6
  • 17
  • This works great, thank you so much! But I have two questions, I see you query the dom to get all the anchors, how is this method different from selecting by tag name? Also I see that you add an event listener where I try to set my function directly to the onClick. – gdc3000 Apr 09 '15 at 13:16
  • I would also cache the array length: `for (i = 0, l = anchors.length; i < l; i += 1)` but that's my personal taste. Depending on the number of anchors on the page, tho, that might give a improvement in performance. – Andy Apr 09 '15 at 13:18
  • In this case, `getElementsByTagName()` would work fine. I prefer `querySelector()` and `querySelectorAll()` since they are easier to use; you just put in the selector like you would with CSS without having to choose the correct method. – s4nji Apr 09 '15 at 13:38
  • Regarding `onclick` or `addEventListener("click")`, check http://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick – s4nji Apr 09 '15 at 13:40
1

Here's a shorter version if browser supports Array.prototype.forEach (most modern browsers do)

var anchors = document.querySelectorAll("a");
    anchors.forEach(function(a) { 
        a.addEventListener("click", function() {
             alert("triggered!");
        });
    });
<a href="#">test1</a>
<a href="#">test2</a>
krlm
  • 817
  • 7
  • 18
  • 1
    Not quite true - Array type has a .forEach method, but yes, my fault, I forgot that the result of querySelectorAll isn't an Array type but a NodeList type. – krlm Apr 09 '15 at 13:29