开发者

jquery selector - Select value not inside another nested tag

Is it possible to select the value of a tag which is not inside another nested tag?

For example in the following code I want to get ' Text I want to select' from $('#example').

<td id="example">
    <a> Text I don't want to select</a>
    <span> Other text I don't want to select</span>
    Text I want开发者_如何学编程 to select
    <anyOtherTag> Other text I don't want to select</anyOtherTag>
</td>

Thanks.


You can use .contents() and .filter() down to text node types (nodeType == 3), like this:

var text = $("#example").contents().filter(function() { 
              return this.nodeType == 3; 
           }).text();
alert($.trim(text));

You can try it out here. since .text() gets all text nodes, including the other whitespace, you probably want to $.trim() (since IE<9 doesn't have String.trim()) the result like I have above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜