Mr Speaker

Nifty jQuery trick: setting attributes

I've been knee deep in the jQuery source code recently. It's all gooey, but you do get to see some snazzy things. Today's nifty jQuery trick is about programmatically setting attribute values via a function. To follow along at home you'll need some scissors, a length of string, and some double sided tape...

We all know that you can grab attribute values using jQuery's attr method. For example, to check if a checkbox is checked you check the checkbox's checked, um, value:
var checked = $("chkNoMail").attr("checked");
And, of course, to set attributes we simply pass the value in as the second parameter: $("<div></div>").attr("id", "myDiv1");
Ok, ok... buuuut, there's also another version of the attr method that accepts not a lowly string... but a mighty function!

The function can implement whatever logic you want, but it needs to return the value that you want the attribute to have. For example, if you want to invert the "selected" values of a multi-select box:

$("selBox").children()
		.attr( "selected", function(){
			return !$(this).attr( "selected" );
		});

Nice! Certainly saves us an extra .each call, and keeps your jQuery gravy-train going. It can also be used to add IDs to a bunch of elements you need to ID:

$("div").attr( "id", function( i ){
	return "myDiv" + i;
}

End tip.

2 Comments

  1. That sweet ass sweet. Thanks.

    Thursday, November 26, 2009 at 9:42 pm | Permalink
  2. You just won the game.

    Thursday, November 26, 2009 at 11:25 pm | Permalink
Captcha! Please type 'radical' here: *
How did you find this thingo? *