Is there a way to get all text from the rendered page with JS?

Stavros Korokithakis picture Stavros Korokithakis · Jun 7, 2010 · Viewed 14k times · Source

Is there an (unobtrusive, to the user) way to get all the text in a page with Javascript? I could get the HTML, parse it, remove all tags, etc, but I'm wondering if there's a way to get the text from the alread rendered page.

To clarify, I don't want to grab text from a selection, I want the entire page.

Thank you!

Answer

Max G J Panas picture Max G J Panas · May 15, 2012

All credit to Greg W's answer, as I based this answer on his code, but I found that for a website without inline style or script tags it was generally simpler to use:

var theText = $('body').text();

as this grabs all text in all tags without one having to manually set every tag that might contain text.

Also, if you're not careful, setting the tags manually has the propensity to create duplicated text in the output as the each function will often have to check tags contained within other tags which results in it grabbing the same text twice. Using one selector which contains all the tags we want to grab text from circumvents this issue.

The caveat is that if there are inline style or script tags within the body tag it will grab those too.

Update:

After reading this article about innerText I now think the absolute best way to get the text is plain ol vanilla js:

document.body.innerText

As is, this is not reliable cross-browser, but in controlled environments it returns the best results. Read the article for more details.

This method formats the text in a usually more readable manner and does not include style or script tag contents in the output.