获取元素的内容而不显示其子元素 [英] Getting the contents of an element WITHOUT its children
问题描述
我有一个温和的偏好,在纯JS中解决这个问题,但如果jQuery版本更简单,那么jQuery也很好。实际情况是这样的
I have a mild preference in solving this in pure JS, but if the jQuery version is simpler, then jQuery is fine too. Effectively the situation is like this
<span id="thisone">
The info I want
<span id="notthisone">
I don't want any of this nonsense
</span>
</span>
我实际上想要获得
信息我想
但不是
我想要的信息我不想要任何这些废话
我特别不想要
我想要的信息< span id =notthisone>我不想要任何这些废话< / span>
,不幸的是我现在得到的......
I effectively want to get
The info I want
but not
The info I want I don't want any of this nonsense
and I especially don't want
The info I want <span id="notthisone"> I don't want any of this nonsense </span>
which is unfortunately what I am getting right now...
我该怎么做?
推荐答案
仅限js:
尝试一下: http://jsfiddle.net/g4tRn/
var result = document.getElementById('thisone').firstChild.nodeValue;
alert(result);
使用jQuery:
试一试: http:// jsfiddle.net/g4tRn/1
var result = $('#thisone').contents().first().text();
alert(result);
奖金:
如果您想要获得外部< span>
中的其他文本节点,可以做这样的事情:
If there are other text nodes in the outer <span>
that you want to get, you could do something like this:
尝试一下: http://jsfiddle.net/g4tRn/4
var nodes = document.getElementById('thisone').childNodes;
var result = '';
for(var i = 0; i < nodes.length; i++) {
if(nodes[i].nodeType == 3) { // If it is a text node,
result += nodes[i].nodeValue; // add its text to the result
}
}
alert(result);
这篇关于获取元素的内容而不显示其子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!