Paolo
Paolo

Reputation: 2472

The shortest way of modifying attributes in jQuery

I am doing this:

$("td.myTD").each( function(){
    var rowspan = $(this).attr("rowspan");
    rowspan = parseInt(rowspan) + 1;
    $(this).attr("rowspan", rowspan);                            
});

(incrementing by one the rowspan for all the td with class myTD). Is there a shorter way of writing it?

In a perfect world I would like to write soemething like this:

$("td.myTD").attr("rowspan", someMagicHereToGetTheAttrValueForEachFoundElement() + 1);

Is it possible?

Upvotes: 4

Views: 137

Answers (2)

palaѕн
palaѕн

Reputation: 73896

You can do this using the .attr( attributeName, function(index, attr) ):

$("td.myTD").attr("rowspan", function(index, attr){
    return parseInt(attr, 10) + 1;
});

Here, the above code uses a function which takes the index position of the element in the set and the old attribute value as arguments. And then the function returns a new attribute value based on the old attribute. This use of a function to compute attribute values is particularly useful when modifying the attributes of multiple elements at once.

For more information, see the attr function(index, attr) documentation.

Upvotes: 14

Barmar
Barmar

Reputation: 780869

.attr() can take a function that returns the new value from the old one:

$("td.myTD").attr("rowspan", function(i, old) { return +old+1 });

DOCUMENTATION

Upvotes: 6

Related Questions