0

I am trying to truncate the text in a paragraph. Paragraph has span tags inside so the script which I have written is counting the text inside the paragraph (including span tag content).

And end result (rendered text) is eliminating the span tag (I need to apply different style for span tag text so it is mandatory to retain the span tag).

So how do I count only direct content of paragraph but not the span text inside it.

Here is the script used for truncation

    var showChar = 50;
    var moretext = "more...";
    var lesstext = "less";
    $('p').each(function() {
        var content = $(this).text();

        if(content.length > showChar) {

            var c = content.substr(0, showChar);
            var h = content.substr(1, content.length - showChar);

            var html = c + '<span class="more"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';

            $(this).html(html);
        }    
    });  
    $(".morelink").click(function(){
        if($(this).hasClass("less")) {
            $(this).removeClass("less");  
            $(this).html(moretext);
        } else {
            $(this).addClass("less");
            $(this).html(lesstext);
        }
        $(this).parent().prev().toggle();
        $(this).prev().toggle();
        return false;
    });

DEMO

1 Answers1

2

You can only select text node inside p tag using:

var contents=$(this).contents().filter(function() {
    return this.nodeType == 3;
}).text();

Well the second approach is slow as it involve cloning the element, finding children and then removing them. But here is how you can do it.

var contents= $(this).clone()
        .children()
        .remove()
        .end()
        .text();
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
  • In this case end result is not showing span text at all. it is totally removed. http://jsbin.com/pinun/6/ –  Jan 08 '15 at 07:37
  • You need to only do this while making the count and not while generating the DOM. – Milind Anantwar Jan 08 '15 at 07:40
  • I need solution for generating DOM –  Jan 08 '15 at 07:46
  • You have asked `how do I count only direct content of paragraph but not the span text inside it.` what exactly do you want. – Milind Anantwar Jan 08 '15 at 07:51
  • Oh sorry for the only question line included that. I also added `(I need to apply different style for span tag text so it is mandatory to retain the span tag)`. It would be great if you can help with this. –  Jan 08 '15 at 08:56
  • you can append style while building span element. – Milind Anantwar Jan 08 '15 at 09:01