DOM中文本节点索引方法

问题

对于 jquery 接口text()只能取到有标签的 dom对象中 文本内容。

如果索引对象本身就是文本节点,则不好索引到, 没有相关的索引选择器。

 

例如:

对于<input>aaa 形式的代码, $("input").next().text(), 则不能返回 aaa。

 

下面有讨论使用jquery索引的方法, 目标是在某个标签下, 找到所有 text node的 对象:

http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery

var getTextNodesIn = function(el) {
    return $(el).find(":not(iframe)").addBack().contents().filter(function() {
        return this.nodeType == 3;
    });
};

getTextNodesIn(el);

 

解决方法

期望使用dom原生api获取 text node值。

https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling

 

例如:

对于<input>aaa 形式的代码, $("input").get(0).nextSibling.nodeValue, 则不能返回 aaa。

 

注释:

对于返回的text内容, 浏览器往往会在前面带有空格, 在后面带有换行, 则使用 string.replace方法去除。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FString

 

originalstr = string.replace(str, /[\w]/g,  "")

 

trim接口也可以试试。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值