![](/img/trans.png)
[英]How to extract / edit an attribute from a html tag using javascript or angularjs?
[英]How to extract text directly under an HTML tag using Javascript
我需要提取直接在HTML标记下的文本。 例如,如果我的HTML看起来像:
<span>This is Outside Text
<span>This is Inside Text</span>
</span>
那么我需要一种方法仅提取“这是外部文本”而不是“这是内部文本”。 我已经尝试过“ innerHTML”,“ innerText”,“ textContent”,还尝试使用RegEx (尽管我不太擅长),但是我找不到解决方案,任何帮助将不胜感激。
请注意,由于某些技术限制,我只需要使用“普通” Javascript,而不要使用jQuery (我知道只不过是Javascript,但是我不能在解决方案中使用它)
使用您的HTML结构,您可以尝试一下-DEMO
alert ( document.querySelector( "span" ).firstChild.nodeValue );
你可以这样 如果第二个跨度之后还有更多文本,它也可以使用。
<span id="span1">This is Outside Text
<span id="span2">This is Inside Text</span>
</span>
var element = document.getElementById("span1");
var element2 = document.getElementById("span2");
var text = element.textContent.replace(element2.textContent, "");
alert(text);
您正在寻找文本子代(类型3的childNodes):
var children=document.getElementById("mySpan").childNodes,
count=children.length,
text="";
for (var i=0;i<count;i++) {
if (children[i].nodeType==3) {
text+=children[i].nodeValue;
}
}
现场演示: http : //jsfiddle.net/aDgPj/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.