0

What am I doing wrong here? Not well versed in js, so assuming I'm doing my for loop wrong.

<div class="date-widget">
  hello1
</div>
<div class="date-widget">
  hello2
</div>

js

$(document).ready(function() {

  var utcInstances = $('.date-widget');

  for (i = 0; i < utcInstances.length; i++) {
    utcInstances[i].text("new text");
  }

});

error:

TypeError: utcInstances[i].text is not a function

http://jsfiddle.net/0jkwasqc/1/

5
  • 2
    use utcInstances[i].textContent = "new text"; Commented Oct 21, 2020 at 20:02
  • 2
    When you index a jQuery collection, the values are DOM elements, not jQuery objects. Commented Oct 21, 2020 at 20:02
  • You don't need a loop, just do utcInstances.text("new text"); if you want to give them all the same text. Commented Oct 21, 2020 at 20:03
  • they will all be unique and dynamic names, I just put "new text" in the fiddle for brevity, my fault there Commented Oct 21, 2020 at 20:05
  • utcInstances.eq(i).text() Commented Oct 21, 2020 at 20:30

1 Answer 1

2

It's jQuery that you'll need more practice with. Specifically when you want to loop through a jQuery collection, you should use .each().

Each item in the collection is a DOM object, not a jQuery object, so you'll have to wrap it before calling .text on it.

$(document).ready(function() {

  var utcInstances = $('.date-widget');

  utcInstances.each( (i, instance) => {
    $(instance).text("new text");  // Wrap instance DOM object into a jQuery object before calling .text
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-widget">
  hello1
</div>
<div class="date-widget">
  hello2
</div>

Sign up to request clarification or add additional context in comments.

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.