最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - In jQuery, what's the difference between text() and innerHTML? - Stack Overflow

programmeradmin8浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 4

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 calling innerText/textContent on a HTML Element.
  • The jQuery 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.

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.

发布评论

评论列表(0)

  1. 暂无评论