tags:

views:

93

answers:

5

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.

+9  A: 

use each:

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

$("a").each(function(){
    //do something with the element here.
});
akellehe
"the element" that akellehe mentions is referenced via the `this` keyword inside the function.
Matt Huggins
+3  A: 

jQuery provides this ability inherently.

$('a').do_something();

Will do_something() to every a on the page. So:

$('a').addClass('fresh'); // adds "fresh" class to every link.

If what you want to do requires looking at the properties of each a individually, then use .each():

$('a').each( function(){
  var hasfoo = $(this).hasClass('foo'); // does it have foo class?
  var newclass = hasfoo ? 'bar' : 'baz'; 
  $(this).addClass(newclass); // conditionally add another class
});
Ken Redler
+2  A: 
$('a').each(function(i){
    $(this).attr('href','xyz');
});
Moin Zaman
A: 

$('a').each(function() {
// The $(this) jQuery object wraps an instance
// of an anchor element.
});

Chris Hutchinson
+5  A: 

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.

Nick Craver
+1 for cheaper implementations
Matt Huggins