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?
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.
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With