Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get whitespace using jQuery's .html() or .text()

Tags:

html

jquery

I have the following HTML:

<div> </span>
<span>  </span>

How can I get an .innerHTML (or .innerText) including the original whitespace? I tried jQuery's .html() and .text(), but they return an empty string.

like image 203
WHITECOLOR Avatar asked Jan 19 '23 06:01

WHITECOLOR


2 Answers

Keep in mind that HTML ignores continuous whitespace. So if you have more than 1, it won't show up. If the jQuery .html() method isn't working for you (maybe they trim inside), you could also just get at the same inner html directly

alert($('#div').get(0).innerHTML)
like image 75
JohnP Avatar answered Jan 29 '23 13:01

JohnP


you need to use .contents() then get the nodeValue... something like this,

$('span').contents()[0].nodeValue

here's a fiddle

like image 21
Reigel Avatar answered Jan 29 '23 14:01

Reigel