简体   繁体   English

Javascript:在包含其他嵌套标签的范围内获取纯文本

[英]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 谨在此提醒您,我当然已经读过第一篇: Javascript在<span>元素内获取文本

However, my case is not that easy, let alone because I need to do it natively, without jQuery . 但是,我的情况并不是那么容易,更不用说了,因为我需要在没有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. 我已经尝试了所有可以想象得到的方法,但是我不能说我尝试过的任何“解决方案”都是很好的解决方案,因为感觉就像是花了很多力气拿走了整个 innerHTML然后对它进行了sed风格的正则表达式魔术。

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. 顺便说一句,我还发现,即使nextSibling()在这里也无法工作。

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: 如果您确实需要从文本JavaScript中剥离HTML,则可以使用如下函数:

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/ 请检查以下内容: http : //jsfiddle.net/shershen08/7fFWn/3/

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. 如果您只想获取元素内的文本节点,我认为您需要遍历元素的childNodes并获取文本节点。 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). 这是一个简单快捷的函数示例,该函数将仅从给定元素中获取文本节点(它还会跳过任何仅包含空格的文本节点,因为这些文本节点通常是由于HTML格式化而添加的,但实际上并不是对人类而言毫无意义)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM