Jinbom Heo
Jinbom Heo

Reputation: 7400

Jquery, Extract child text

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.

Upvotes: 3

Views: 256

Answers (3)

SeanCannon
SeanCannon

Reputation: 77956

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.

Upvotes: 6

Ramiz Uddin
Ramiz Uddin

Reputation: 4259

Another Trick:

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

Upvotes: 0

Atiqul Alam
Atiqul Alam

Reputation: 181

Hope it will work

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

targetString is you required.

Upvotes: 2

Related Questions