Mdd
Mdd

Reputation: 4430

Test for innerText or textContent inside loop

JSLint throws the following error that I am not sure how to resolve:

Error: Don't declare variables in a loop.

Line: var text = item.innerText || item.textContent

My question is how do I get for support of innerText or textContent and use the correct method while looping through elements?

Here's my example. I am writing the class of the elements next to the text. I'd like to have the same results, but test for innerText or textContent outside of the for-loop.

Fiddle: http://jsfiddle.net/PwwjK/

HTML:

<p class="test">1</p>
<p class="test">2</p>
<p class="test">3</p>

JavaScript:

(function () {
  'use strict';
  var list = $('.test');

  for (var i = 0, item; item = list[i]; i++) {

    if (i === 1) {
        //Add new class attribute.
        item.className = item.className + ' hello';
    };

    var text = item.innerText || item.textContent

    item.innerHTML = text + ' ' + item.className;

  };

}());

Upvotes: 0

Views: 2337

Answers (2)

Rayan Bouajram
Rayan Bouajram

Reputation: 743

You'll have to declare var text outside the for-loop for this test to pass.

(function () {
  'use strict';
  var list = $('.test'),
      text; // text is declared here.

  for (var i = 0, item; item = list[i]; i++) {
    if (i === 1) {
        //Add new class attribute.
        item.className = item.className + ' hello';
    };

    text = item.innerText || item.textContent

    item.innerHTML = text + ' ' + item.className;
  };
}());

Also, here's a resourceful link that may have an answer as to why jsLint asks you to declare the variables on the top: JSLint error: Move all 'var' declarations to the top of the function

Upvotes: 2

Barmar
Barmar

Reputation: 782107

Declare the variable outside the loop, and assign it inside the loop.

(function () {
  'use strict';
  var list = $('.test');
  var text;

  for (var i = 0, item; item = list[i]; i++) {

    if (i === 1) {
        //Add new class attribute.
        item.className = item.className + ' hello';
    };

    text = item.innerText || item.textContent

    item.innerHTML = text + ' ' + item.className;

  };

}());

Upvotes: 1

Related Questions