Reputation: 2393
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/
Upvotes: 0
Views: 626
Reputation: 8076
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>
Upvotes: 2