The shortest way to change attributes in jQuery

I'm doing it:

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

(increment by one column for all td with class myTD). Is there a shorter way to write it?

In an ideal world, I would like to write like this:

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

Is it possible?

+4
source share
2 answers

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

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

DOCUMENTATION

+6
source

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

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

Here in the above code, a function is used that takes the position of the index of the element in the set and the value of the old attribute as arguments. And then the function returns the new attribute value based on the old attribute. This use of a function to calculate attribute values ​​is especially useful when changing the attributes of several elements at the same time.

See the attr (index, attr) documentation for more information.

+14
source

Source: https://habr.com/ru/post/1489909/


All Articles