newBike
newBike

Reputation: 15002

Extract plain text from DOM nodes

I got the selection information from:

var childNodes = window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode.childNodes

The actual data will be:

<p>
    Something I’ve not covered much so far is some of the newer parts of JavaScript. 
    That is, methods in ECMASscript 5 that are not so 
    <span class="mydict_highlighted">commonly</span>
    used due to browser support, and of course the new features in ECMAScript 6. 
    Today I want to take a look at the new Array methods in ES5, such as 
    <code class="highlighter-rouge">map</code>
    and 
    <code class="highlighter-rouge">filter</code>
    .
</p>

How could I extract the text only from the childNodes?

inline

Upvotes: 2

Views: 3174

Answers (1)

gyre
gyre

Reputation: 16779

About element.textContent

Use element.textContent to get the text inside an HTML element with all descendant HTML tags stripped. If you wish, you can add .trim() to the end to remove leading and trailing whitespace from the returned text.

window.getSelection().getRangeAt(0).commonAncestorContainer.parentNode.textContent.trim()

About element.innerText

Alternatively, one can use the element.innerText property (once proprietary to IE, but later added to the web standards) to do almost the same thing. textContent will more closely match the actual string data stored inside your DOM nodes (it is essentially a concatenation of every text node), whereas innerText attempts to be more "helpful" by trying to mimic the style of the page, e.g. by omitting the text from script/style tags and visually hidden elements. The one you prefer will vary depending on the use case, but I find I use textContent the majority of the time. For more information, I would highly recommend you check out this list of differences between the two properties on MDN.

Demo for textContent

var element = document.getElementById('content')

console.log(element.textContent.trim())
<div id="content">

<p>Something I’ve not covered much so far is some of the newer parts of JavaScript. That is, methods in ECMASscript 5 that are not so <span class="mydict_highlighted">commonly</span> used due to browser support, and of course the new features in ECMAScript 6. Today I want to take a look at the new Array methods in ES5, such as <code class="highlighter-rouge">map</code> and <code class="highlighter-rouge">filter</code>.</p>

</div>

Upvotes: 4

Related Questions