我有这个HTML代码

<div id="mydiv">
    <div>
        <span>Text inside span</span>
        Text next to span
    </div>
    <div>
        Contents inside the 2nd div element...
    </div>
</div>

我想获取“跨度旁的文本” 。我尝试过此代码JQuery代码
var a = $('#mydiv div').first().find('span').parent().text();
alert(a);

上面的jquery代码的输出是这样的:
Text inside span
Text next to span

只获得“跨度后的文本” 应该怎么做?

最佳答案

var a = $('#mydiv div').first().contents().filter(function() {
    return this.nodeType == 3;
}).text();

这将获取所选div的内容,并过滤匹配的集,仅返回带有nodeType == 3的元素,即文本节点。

关于jquery - 使用jQuery获取span元素后的文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6925088/

10-13 01:38
查看更多