Reputation: 1359
I have the following jquery code
var arr = $(".input-span").children()
for (var i =0;i<arr.length;i++){
console.log(arr[i].text())
}
and the following html code
<div class="input-span">
input1
</div>
<div class="input-span">
input2
</div>
However when I am executing the previous jquery code, I end up with the following error
text() is not a function
Upvotes: 0
Views: 126
Reputation: 8592
You have HTML elements in your array, not jQuery elements. So:
$(arr[i]).text()
Upvotes: 0
Reputation: 24638
You can use the .eq(n)
jQuery method to select the single jQuery object at index n
and you can use .text()
and other jQuery method on the resulting object:
var arr = $(".input-span")
for (var i = 0; i < arr.length; i++) {
console.log(arr.eq(i).text());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-span">
input1
</div>
<div class="input-span">
input2
</div>
Upvotes: 0
Reputation: 780818
When you access a jQuery collection using an array index, it returns the DOM element, not a jQuery object. So you can't call jQuery methods on it. You should use a native DOM property like innerText
, or use arr.eq(i)
method to get the jQuery object.
Also, your .input-span
elements don't have any children, so arr
is empty. I removed the call to .children()
.
var arr = $(".input-span")
for (var i = 0; i < arr.length; i++) {
console.log(arr[i].innerText)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-span">
input1
</div>
<div class="input-span">
input2
</div>
Upvotes: 3