开发者

Jquery, Extract child text

开发者 https://www.devze.com 2023-03-20 00:17 出处:网络
Here is html code, <li class=\"comment-content\"> Target String!!! <span class=\"comment-time\">2011-07-13 17:08:39</span>

Here is html code,

<li class="comment-content">
    Target String!!!
    <span class="comment-time">2011-07-13 17:08:39</span>
    <a title="comment" class="bottoml cof-comment" href="#">comment</a>
    <a title="modify" class="bottoml cof-comment" href="#">modify</a>&nbsp;&nbsp;
    <a title="delete" class="bottoml cof-comment" href="#">delete</a></li>
</li>

I can get comment-content's text using jquery like this,

$(".comment-content").text();

the result is :

Target String!!! 2011-07-13 17:08:39开发者_开发技巧 comment modify delete

my question, can I get the string "Target String!!!" only using jquery? without sub tag's text, direct child text only I mean.


Like this:

$('.comment-content').contents().filter(function(){ return this.nodeType == 3; });

Example: http://jsfiddle.net/AlienWebguy/FGAXE/

As you can see on the MDN Node.nodeType explanation, the constant TEXT_NODE = 3, so that's what we need to look for.


Hope it will work

var content = $(".comment-content").html();
var targetString = content.substring(0,content.indexOf('<'))

targetString is you required.


Another Trick:

                $(this)
                    .clone()
                    .children()
                    .remove()
                    .end()
                    .text();
0

精彩评论

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