0

in this for loop why not loop all the input ?

I tried in jquery each it work.. but I want use for loop do I miss something

I want to add class to all input not has class .typeLimit , and select item in the loop

https://jsfiddle.net/6v8arLqa/

var type = 'number';

for (var i = 0; i < $('input[data-type-limit="' + type + '"]').not('.typeLimit').length; i++) {
    console.log(i)
    var input = $('input[data-type-limit="' + type + '"]').not('.typeLimit').eq(i);
    console.log(input)
    input.addClass('typeLimit');
 }


<input type="text" data-type-limit="number" placeholder=":1">
<input type="text" data-type-limit="number" placeholder=":2">
<input type="text" data-type-limit="number" placeholder=":3">
<input type="text" data-type-limit="number" placeholder=":4">
<input type="text" data-type-limit="number" placeholder=":5">
<input type="text" data-type-limit="number" placeholder=":6">
<input type="text" data-type-limit="number" placeholder=":7">
<input type="text" data-type-limit="number" placeholder=":8">
<input type="text" data-type-limit="number" placeholder=":9">
<input type="text" data-type-limit="number" placeholder=":10">

test with each

$.each($('input[data-type-limit="' + type + '"]').not('.typeLimit'), function(i, val) {
console.log(i)
      var input = $(this);
      input.addClass('typeLimit');
  });
0

1 Answer 1

1

Because every time you go through the loop, the contents of $('input[data-type-limit="' + type + '"]').not('.typeLimit') are changing so you're going to skip some elements. To prevent this problem (and be much more efficient) you can cache the results and work through those.

var $noTypeLimit = $('input[data-type-limit="' + type + '"]').not('.typeLimit');
for (var i = 0; i < $noTypeLimit.length; i++) {
  var $input = $noTypeLimit.eq(i);
  $input.addClass('typeLimit');
}

Or if all you're doing is adding a class to them, you can simplify it even more.

$('input[data-type-limit="' + type + '"]')
  .not('.typeLimit')
  .addClass('typeLimit');
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for reply, it works I use first method cache them, if I doing this is there any different performance compare with jquery each
This way is faster than either of the other options. You save yourself additional DOM queries and you don't have to perform a bunch of other function calls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.