Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 567
Paolo Avatar asked Dec 01 '22 03:12

Paolo


2 Answers

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.

like image 111
palaѕн Avatar answered Dec 02 '22 16:12

palaѕн


.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

like image 25
Barmar Avatar answered Dec 02 '22 16:12

Barmar