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.

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()+"-");

So how can I get to the innerText?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With