My html is -
我的HTML是 -
<div>
<span>spanText</span>
nonspantext
</div>
My js is -
我的js是 -
$(function(){
alert($("div").text());
});
What I want to get is "nonspantext" as alert.
Fiddle to begin is here - http://jsfiddle.net/UHr2x/
我想得到的是“非全文”作为警报。小提琴开始就在这里 - http://jsfiddle.net/UHr2x/
2 个解决方案
#1
1
Well, that's quite a good use case to use good old DOM API.
好吧,使用好的旧DOM API是一个很好的用例。
$('span')[0].nextSibling.nodeValue;
And a working example.
一个工作的例子。
Seems more efficient than James' solution.
似乎比詹姆斯的解决方案更有效率。
#2
7
You can use .contents()
to get the contents (including text nodes) of an element, and then filter the result to leave only the text nodes:
您可以使用.contents()来获取元素的内容(包括文本节点),然后过滤结果以仅保留文本节点:
$("div").contents().filter(function () {
return this.nodeType === 3;
}).text();
Here's a working example. Notice that the result includes new lines, so you might want to trim it before using it.
这是一个有效的例子。请注意,结果包含新行,因此您可能希望在使用之前对其进行修剪。
#1
1
Well, that's quite a good use case to use good old DOM API.
好吧,使用好的旧DOM API是一个很好的用例。
$('span')[0].nextSibling.nodeValue;
And a working example.
一个工作的例子。
Seems more efficient than James' solution.
似乎比詹姆斯的解决方案更有效率。
#2
7
You can use .contents()
to get the contents (including text nodes) of an element, and then filter the result to leave only the text nodes:
您可以使用.contents()来获取元素的内容(包括文本节点),然后过滤结果以仅保留文本节点:
$("div").contents().filter(function () {
return this.nodeType === 3;
}).text();
Here's a working example. Notice that the result includes new lines, so you might want to trim it before using it.
这是一个有效的例子。请注意,结果包含新行,因此您可能希望在使用之前对其进行修剪。