JQuery: How to remove the redundancy of this code?

    clone.find('[id]').each(function() {
        id = $(this).attr('id');
        ind = id.search(/\d+$/);
        $(this).attr('id', id.substr(0,ind)+id_counter);
    });
    clone.find('[for]').each(function() {
        id = $(this).attr('for');
        ind = id.search(/\d+$/);
        $(this).attr('for', id.substr(0,ind)+id_counter);
    });

      

I know I can find elements that have either an attribute id

or an attribute for

, but how do I know which one I need to set?

+2


source to share


3 answers


If all you are trying to do is minify the code, you can ...

 function doTheseThings(element) {
    clone.find(element).each(function() {
       var id = $(this).attr('id');
       var ind = id.search(/\d+$/);
       $(this).attr('id', id.substr(0,ind)+id_counter);
    });
 }

 doTheseThings('[id]');
 doTheseThings('[for]');

      

EVEN BETTER:



I decided to link my first answer with some of @SHiNKiROU's ideas and add some more Jquery-ish syntaxes:

var items = ['[id]', '[for]'];
$.each(items, function (index, element) {
    clone.find(element).each(function() {
       var id = $(this).attr('id');
       var ind = id.search(/\d+$/);
       $(this).attr('id', id.substr(0,ind)+id_counter);
    });
});

      

+3


source


var list = ['id', 'for']
for (var i in list) {
  var v = list[i];
  clone.find('[' + v + ']').each(function() {
    id = $(this).attr(v);
    ind = id.search(/\d+$/);
    $(this).attr(v, id.substr(0,ind)+id_counter);
  });
}
delete list;

      



+3


source


Well, the redundancy is that the same code applies to different attributes, so you don't account for them:

$.each(['id', 'for'], function (ignr, attr) {
  clone.find('['+attr+']').each(function() {
      val = $(this).attr(attr);
      ind = val.search(/\d+$/);
      $(this).attr(attr, val.substr(0,ind)+id_counter);
  });
});

      

Then, if you want, you can remove the local variable to shorten it, but I'm not sure if this is an improvement:

$.each(['id', 'for'], function (ignr, attr) {
  clone.find('['+attr+']').each(function() {
      val = $(this).attr(attr);
      $(this).attr(attr, val.substr(0,val.search(/\d+$/))+id_counter);
  });
});

      

+1


source







All Articles