查找文本节点 [英] Finding text node

查看:107
本文介绍了查找文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个聪明的jQuery选择器用于选择如下的文本节点:

Is there a clever jQuery selector for selecting a text node like this:

<div><input type="text">one <span>two</span> three</div>

我想从上面的标记中获得三个这样的强标签:

I would like to get three from the markup above and wrap it in a strong tag like this:

<div><input type="text">one <span>two</span> <strong>three</strong></div>


推荐答案

这里是如何使用jQuery选择文本节点: / p>

Here is how to select text nodes using jQuery:

var x = $('div') 
  .contents() 
  .filter(function() { 
    return this.nodeType == 3;
    //return this.nodeType == Node.TEXT_NODE;  this works unless using IE 7
  }); 

在你的示例中,x将包含索引0处的one和索引1处的three。像Keith Rousseau说的,你不能真正地抓住这个文本,但如果你知道这将是最后你可以得到它像这样:

In your example x will then contain 'one' at index 0 and 'three' at index 1. Like Keith Rousseau said, you can't really just grab that text, but if you know it will be last you can get it like this:

var elemThree = x[x.length-1];

您也可以像这样添加strong标签:

You can also add the strong tag like this:

$(x[x.length-1]).wrap("<strong></strong>");

This questions describes selecting text nodes with jQuery (my first code snippet).

这篇关于查找文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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