Reputation: 701
Just for you guys to note, of course I have read this first: Javascript get text inside a <span> element
However, my case is not that easy, let alone because I need to do it natively, without jQuery
.
Supposing we have this on an arbitrary web page:
<span id="entry1" class="entries">
<a href="http://whereyourpicis.at/pic.jpg" style="float: right; margin-left: 1em;"><img src="http://whereyourpicis.at/pic.jpg" border="0"></a>
++ This is the plain text we want to get from the SPAN block. ++
<span id="nested2"><a onclick="doSomething()">Action!</a></span>
</span>
I've tried anything imaginable, but I can't say any of the "solutions" I tried was a good one, since it feels like a total kludge taking the whole innerHTML and then doing some sed
-style regex magic on it.
There must be a more elegant way to accomplish this, which is why I'm asking here.
BTW I've also found out that even nextSibling()
cannot work here.
Upvotes: 3
Views: 2018
Reputation: 1944
If you want to get only the text nodes within an element, I think you'll need to iterate over the element's childNodes and fetch the text nodes. Here's a quick-and-dirty example of a function that will fetch only the text nodes from a given element (it also skips any text nodes that are just whitespace, since those are often added as a result of HTML formatting but don't really mean anything to a human).
Upvotes: 0
Reputation: 9993
I am not sure this is what you need, because you didn't specify what you need to be an exact output in your example code.
If you need to literally Strip HTML from Text JavaScript you could use function like this:
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
please check this: http://jsfiddle.net/shershen08/7fFWn/3/
Upvotes: 2