I have div elements and hold text/string inside them, then I try to iterate them, and text() doesn't work, but innerHTML work just fine.
var arr = $('div.elm');
$.each(arr, function(i,j){
alert(j.text()); // it's not working
console.log(j.text()); // nothing's in log
alert(j.innerHTML); // works fine!
});
text()
is a jQuery method, innerHTML
is an DOM Element attribute.
When you call $.each
on a jQuery object, the second parameter you receive (the element) will be a DOM element, not a jQuery object.
text()
method is similar to calling innerText
/textContent
on a HTML Element.html()
method is similar to calling innerHTML
on a HTML Element.If you want to use jQuery methods on your parameter passed in by each
, you have to wrap it in a jQuery object:
$.each(arr, function(i,j){
alert($(j).text());
});
In your case, you should wrap the object in a jQuery object to use the text()
method:
$.each(arr, function(i,j){
alert($(j).text());
console.log($(j).text());
alert(j.innerHTML);
});
innerHTML
is an element attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With