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
That sweet ass sweet. Thanks.
You just won the game.