4

How can I get plain text from an element?

<div id="summary_header">
    <span class="heading" style="margin-left: 210px;">This is first line</span><br/>
    <span style="margin-left: 260px;"><b> You are in second line</b></span><br/>
</div>

What's the way to get plain text from this div tag? I want to get plain text as "This is first line You are in second line".

$('summary_header').textContent gives with white spaces.

1
  • Is their is any method in prototypeJs like jQuery text() method. Commented Jan 20, 2011 at 9:15

2 Answers 2

4

If you need a method, no problem. That is the beauty of javascript and it's prototypal inheritance.

Prototype.js allows you to extend the Element object with new methods. Just add this to your scripts:

Element.addMethods({
    getText: function(element) {
        element = $(element);
        return element.innerHTML.strip().stripTags().replace(/\n/g,' ').replace(/\s+/g,' ');
    }
});

That is almost the same as @koko proposed, but I suggest changing each new line character \n to one space instead of removing them, and changing any number of consecutive withe-space characters to single space. This is similar behavior to what browsers do.

When you at that to your scripts, after the prototype.js loads, you can use new method to get plain text:

var plainText = $('summary_header').getText();

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

2 Comments

It would make sense to have the strip after stripTags since there might be extraneous whitespace inside those tags, and the two regular expressions can be collapsed into one: /[\n\s]+/g
Right, both of your comments make sesne. Thanks. To much inspiration by koko's code...
2

It's not very beautiful, but it works. I don't know what you're trying to achieve, but there you go:

var f = $('summary_header').innerHTML.strip().stripTags().replace(/\n/g,'').replace(/\s{2}/g,'');

http://jsfiddle.net/e8uFS/1/

2 Comments

I need a method like text() in jQuery to get plain text form an element. Same way as in PrototypeJS

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.