Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the text only (no tags) from a HTML document?

I have a HTML page, and I want the text only (all text nodes).

Example HTML

<span>hello <strong>sir</strong></span>

Desired Output

hello sir
like image 204
Anusha Avatar asked Mar 16 '11 06:03

Anusha


People also ask

How do I get just the text from HTML in jQuery?

You could use $('. gettext'). text(); in jQuery.

How do I convert HTML text to normal text in Java?

Just call the method html2text with passing the html text and it will return plain text.


1 Answers

Assuming you only want children of body element...

Example HTML

<html><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> Example</title>
</head>
<body>
  a <div>b<span>c</span></div>
</body></html>

JavaScript

var body = document.body;
var textContent = body.textContent || body.innerText;

console.log(textContent);  //   a bc

You need to check for textContent because our good friend IE uses innerText instead.

It is much easier if you have a library such as jQuery, i.e. $('body').text().

Also, it can be achieved on the server side, such as strip_tags() in PHP. However, if you only wanted the body element, you'd need to drill down to it using a DOM parser such as DOMDocument.

like image 193
alex Avatar answered Sep 23 '22 23:09

alex