我有这个HTML代码
<div id="mydiv">
<div>
<span>Text inside span</span>
Text next to span
</div>
<div>
Contents inside the 2nd div element...
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
我想得到"文本旁边的跨度".我试过这段代码JQuery代码
var a = $('#mydiv div').first().find('span').parent().text();
alert(a);
Run Code Online (Sandbox Code Playgroud)
上面的jquery代码的输出是这样的:
Text inside span
Text next to span
Run Code Online (Sandbox Code Playgroud)
如果只获得"文本旁边的跨越",那么正确的做法应该是什么?
Jam*_*ice 50
var a = $('#mydiv div').first().contents().filter(function() {
return this.nodeType == 3;
}).text();
Run Code Online (Sandbox Code Playgroud)
这将获取所选内容div
,并过滤匹配的集合,仅返回带有nodeType == 3
文本节点的元素.
使用此代码:
$('#myDiv')
.contents()
.filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();
Run Code Online (Sandbox Code Playgroud)
小智 7
我明白了:
$('#mydiv div').first().contents().eq(1).text();
Run Code Online (Sandbox Code Playgroud)