3

I prefer the TypeScript forloop over the JQuery each().

I.e. because return and break work more like expected.

Is there an easy way to loop through a JQuery object using TypeScript?

let $elements = $('.text-element');

// error: Type 'JQuery' is not an array type or a string type.
for ( let $element of $elements )
{
}

4 Answers 4

4

You can use jQuery get to return a iterable of the DOM elements (not jQuery elements):

let $elements = $('.text-element');

for (let element of $elements.get()) {
  let $element = $(element);
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

1

Because jQuery's class selector doesn't return an iterator, but a jQuery object. To use a for..of syntax you need to make it an array-like iterable using Array#from.

$(function() {
  const elements = Array.from($('.text-element'));

  for (const element of elements) {
    console.log(element.innerHTML);
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="text-element">
  10
</div>
<div class="text-element">
  20
</div>
<div class="text-element">
  30
</div>

2 Comments

Is Array.from new? The 2.8 typings don't seem to recognize it.
if your browser supports ES6 it should be available
1

The result of $('.text-element') is not a real Array. Try creating an Array from it, first:

let $elements = Array.from($('.text-element'));

for ( let $element of $elements )
{
}

2 Comments

Is Array.from new? The 2.8 typings don't seem to recognize it.
0

jQuery collections have been iterable since v1.12.0 and v2.2.0 (PR, commit), which were released in January 2016:

Symbol/iterator support

We've added support for the Symbol type and iterators via Symbol.iterator added in ES6/ES2015. "Symbol" will be detectable with jQuery.type, and jQuery objects can be iterated with for-of where supported.

for (element of $elements) {
 console.log(element);
}

Sounds like you just need to update your jQuery.

Comments

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.