Iseng Aja
Iseng Aja

Reputation: 79

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 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!
});

Upvotes: 4

Views: 3555

Answers (4)

Matt
Matt

Reputation: 75327

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());
});

Upvotes: 4

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

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.

Upvotes: 2

Keith.Abramo
Keith.Abramo

Reputation: 6965

.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.

Upvotes: 1

tereško
tereško

Reputation: 58454

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.)

Upvotes: 1

Related Questions