使用jQuery获取span元素后的文本 [英] Get the text after span element using jquery

查看:364
本文介绍了使用jQuery获取span元素后的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个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代码

I wanted to get the "Text next to span". I tried this code JQuery code

var a = $('#mydiv div').first().find('span').parent().text();
alert(a);

上面的jquery代码的输出是这样的:

The output of the jquery code above is this:

Text inside span
Text next to span

仅获得跨度旁边的文本" ,应该怎么做?

推荐答案

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

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

This gets the contents of the selected div, and filters the matched set, returning only elements with nodeType == 3, which are text nodes.

这篇关于使用jQuery获取span元素后的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆