Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!
});
like image 843
Iseng Aja Avatar asked Feb 22 '23 18:02

Iseng Aja


2 Answers

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());
});
like image 194
Matt Avatar answered Feb 25 '23 07:02

Matt


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.

like image 31
Nicola Peluchetti Avatar answered Feb 25 '23 08:02

Nicola Peluchetti