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:
$("a").each(function(){
//do something with the element here.
});
akellehe
2010-08-31 15:36:09
"the element" that akellehe mentions is referenced via the `this` keyword inside the function.
Matt Huggins
2010-08-31 15:43:11
+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
2010-08-31 15:36:13
A:
$('a').each(function() {
// The $(this) jQuery object wraps an instance
// of an anchor element.
});
Chris Hutchinson
2010-08-31 15:36:58
+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
2010-08-31 15:39:26