innerHTML without the html, just text [duplicate]
Asked Answered
P

3

31

I've created an e-mail link that automatically populates the necessary information in the body. But, when I do .innerHTML I get a little more than I bargained for.

I want "March, 2012: 12-16"

What I get <B>March, 2012</B>: <FONT color=blue>12</FONT> - <FONT color=blue>16</FONT>

Is there a way to get the innerHTML without the html tags?

.value = undefined
.text = undefined
Pacifier answered 15/3, 2012 at 19:50 Comment(3)
I think there's an innerText property...Proof
Have a look at #822952Corsetti
...I searched for like 20 minutes and couldn't find that. : / thanksPacifier
A
52

You want .textContent in all but older IE, and .innerText in IE (<9).

So, try:

string = (node.textContent===undefined) ? node.innerText : node.textContent;

EDIT: Or, just use GGG's much cleaner string = (node.innerText || node.textContent), since undefined is falsy.

Amylaceous answered 15/3, 2012 at 19:55 Comment(4)
what the... (node.innerText || node.textContent). Although they're not exactly the same...Tyson
Who is GGG? Alter ego?Direful
@Direful web.archive.org/web/20120927230726/http://stackoverflow.com/… (See also If I change my display name, will the change reflect in comments?)Amylaceous
innerText and textContent do have slightly different behaviors (i.e. innerText takes CSS display: hidden into account), so be careful which you use. For my use case, I only wanted human-readable text, for which innerText is the solution (see developer.mozilla.org/en-US/docs/Web/API/Node/…).Uvula
M
7

In the browser that supports the standard, you can use textContent instead of innerHTML. Otherwise you can loop through the next nodes and concatenate them, or using library like jQuery that abstract this approach for you.

Matthia answered 15/3, 2012 at 19:53 Comment(2)
The company is using an older version of IE and textContent returns undefined. innerText worked fine though. Is there any reason why I shouldn't use innerText?Pacifier
innerText is not exactly textContent. If you have to work in a IE-only environment, that's fine I don't see any harm in use it – it's just not standard. Here the refs: msdn.microsoft.com/en-us/library/ms533899(v=vs.85).aspxMatthia
B
3

If you are already using jQuery, you can use .text():

http://jsfiddle.net/vkgYR/

if you are not using it though, you should just go with the other comments since it would be silly to load all of jQuery just for the .text() method

Bullfight answered 15/3, 2012 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.