Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: how do I loop through all 'a' elements?

Tags:

jquery

I want to be able to change all the anchor's properties on a page. But I don't know how to loop through all of them.

like image 276
NullVoxPopuli Avatar asked Aug 31 '10 15:08

NullVoxPopuli


2 Answers

use each:

http://api.jquery.com/each/

$("a").each(function(){
    //do something with the element here.
});
like image 61
KeatsKelleher Avatar answered Sep 21 '22 19:09

KeatsKelleher


You can use .attr() with a function to change a specific property, for example:

$("a").attr("href", function(i, oldHref) {
  return oldHref + "#hash";
});

This is cheaper than .each() since you're not creating an extra jQuery object inside each iteration, you're accessing the properties on the DOM element without doing that.

like image 35
Nick Craver Avatar answered Sep 23 '22 19:09

Nick Craver