开发者

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

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.


use each:

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

$("a").each(function(){
    //do something with the element here.
});


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.


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
});


$('a').each(function(i){
    $(this).attr('href','xyz');
});


You can use jQuery .each() for this purpose:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜