Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: get plain text inside a span which has other nested tags present

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.

like image 547
syntaxerror Avatar asked Sep 15 '26 13:09

syntaxerror


1 Answers

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/

like image 67
shershen Avatar answered Sep 18 '26 03:09

shershen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!