Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get innerText with jQuery instead of innerHTML

I have a figcaption and i would like the text from it. This is what it looks like in the element inspector in chrome. For some reason the 'innerHTML' starts with a return and then a lot of spaces. The 'innerText' however looks good so i'm interested in that.

enter image description here

Online I see I have to use the text() method to get the innerText but it seems to give the innerHTML:

console.log("-"+$(this).find("figcaption").text()+"-");

enter image description here

So how can I get to the innerText?

like image 327
clankill3r Avatar asked Oct 23 '25 19:10

clankill3r


1 Answers

When you create an HTML element such as:

<p>Hello          World</p>

When that is rendered by the browser, whitespace is collapsed by default. The result will be "Hello World". That collapsing of the data happens at browser rendering time. The DOM model contained within the browser maintains the actual text including any white spaces contained within it. As such, what you see on the screen may not be the same as the data contained within the DOM.

The white space stripped data is available via the DOM property called "innerText".

A jsBin sample showing the data has been supplied.

The demonstration code is basically:

HTML

<p id="here">Hello      World</p>
<button>Show</button>

JavaScript

$(function() {
  $("button").click(function() {
    console.log("text: " + $("#here").text());
    console.log("innerText: " + $("#here").prop("innerText"));
  });
});

The console will log:

text: Hello      World
innerText: Hello World

From your original question, the use of the text() method returns the DOM data while the use of prop("innerText") returns the calculated innerText value that the browser built.

like image 106
Kolban Avatar answered Oct 26 '25 08:10

Kolban



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!