Strip for me, please

24 May 2011

How do you get the text from within an element?

Inner Html to the rescue!! Not so fast. We can’t guarantee the markup within the element will be just text, other elements have been known to live in there.


<div id="a">Let me <strong>Strip</strong> for you</div>

So how do we do it?

My first thought was that I would have to knock the dust off my regular expressions to any strip tags that may exist. Luckily, there is a dom method that looks after this, unsurprisingly, it’s not the same for each browser.


var a = document.getElementById('a');
var inner = a.innerHTML; //Let me <strong>Strip</strong> for you
var text = (a.textContent) ? a.textContent : a.innerText; //Let me Strip for you

Nice isn’t it? textContent will work for most, innerText will work for the rest.

Matt Sain

Ramblings of a developer, designer and child subscribe

This blog is a public GitHub repository. If you find an error I will not be surprised... but if you fork and edit the blog and send me a pull request you'd be pretty awesome in my book.

Featured Repos