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
3
  • I think there's an innerText property... Commented Mar 15, 2012 at 19:52
  • 1
    Have a look at stackoverflow.com/questions/822452/… Commented Mar 15, 2012 at 19:53
  • ...I searched for like 20 minutes and couldn't find that. : / thanks Commented Mar 15, 2012 at 19:53

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

what the... (node.innerText || node.textContent). Although they're not exactly the same...
Who is GGG? Alter ego?
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/…).
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.

2 Comments

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?
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).aspx
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.