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!
});
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!
});
Share
Improve this question
asked Oct 10, 2011 at 12:58
Iseng AjaIseng Aja
792 silver badges8 bronze badges
5
- what kind of elements are you iterating over? – John Strickler Commented Oct 10, 2011 at 12:59
-
<div class='elm'>text1</div>
... and so on.. – Iseng Aja Commented Oct 10, 2011 at 13:00 -
2
sometimes you need to re-jquerify :) iterated items... try
$(j).text()
– a.b Commented Oct 10, 2011 at 13:01 - j is not a jQuery object so text() can't be used, you need to wrap it first – Nicola Peluchetti Commented Oct 10, 2011 at 13:02
- @AbdullahBattal: I think "re-jquerify" may be the most awkward made-up programming word I've ever seen. :-) – Blazemonger Commented Oct 10, 2011 at 14:51
4 Answers
Reset to default 4text()
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.
- The jQuery
text()
method is similar to callinginnerText
/textContent
on a HTML Element. - The jQuery
html()
method is similar to callinginnerHTML
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.
http://api.jquery./text/
Unlike the .html() method, .text() can be used in both XML and HTML documents. The result of the .text() method is a string containing the bined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.)
.text()
returns JUST the text of that element and all of its descendant elements, where as .innerHTML
returns all of the HTML in that element.