使用 jquery 获取 span 元素后的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6925088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the text after span element using jquery
提问by Rash Amed
I have this html code
我有这个 html 代码
<div id="mydiv">
<div>
<span>Text inside span</span>
Text next to span
</div>
<div>
Contents inside the 2nd div element...
</div>
</div>
I wanted to get the "Text next to span". I tried this code JQuery code
我想获得“跨度旁边的文本”。我试过这段代码 JQuery 代码
var a = $('#mydiv div').first().find('span').parent().text();
alert(a);
The output of the jquery code above is this:
上面jquery代码的输出是这样的:
Text inside span
Text next to span
What should be the right thing to do to just get only the "Text next to span"?
只获得“跨度旁边的文本”应该怎么做?
回答by James Allardice
var a = $('#mydiv div').first().contents().filter(function() {
return this.nodeType == 3;
}).text();
This gets the contents of the selected div
, and filters the matched set, returning only elements with nodeType == 3
, which are text nodes.
这将获取 selected 的内容div
,并过滤匹配的集合,仅返回带有 的元素nodeType == 3
,这些元素是文本节点。
回答by Sean Don
I got it by this:
我是这样理解的:
$('#mydiv div').first().contents().eq(1).text();
回答by Tushar Ahirrao
Use this code:
使用此代码:
$('#myDiv')
.contents()
.filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();