In jQuery, what's the difference between text() and innerHTML?
I have div elements and hold text/string inside them, then I try to iterate them, and text() doesn't work, but innerH开发者_JAVA技巧TML 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.
- 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.com/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 combined 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.
精彩评论