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?
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?
Share Improve this question asked Jul 5, 2013 at 13:40 PaoloPaolo 2,4726 gold badges34 silver badges45 bronze badges 1-
The
.attr()
method does support a way to do what you are asking, as shown in the answers below, but note that even if it didn't you could shorten the code by eliminating therowspan
variable and using the unary plus operator instead ofparseInt()
:$(this).attr("rowspan", +$(this).attr("rowspan") + 1)
- of course, you'd still need the.each()
that way. – nnnnnn Commented Jul 5, 2013 at 13:52
2 Answers
Reset to default 14You 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 pute 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