views:

14951

answers:

3

I'm trying to figure out how to truncate the first paragraph, and I've tried:

$div.children( ('p:eq(0)').substring(0,100)); 
$div.children( ('p:eq(0)'.substring(0,100)));

But neither have worked...

Here's the complete code (which someone here helped me with!)

$j('#hp-featured-item > div[id^="post-"]').each(function() {
        var $div = $j(this),
                $h2  = $div.find('h2:first'),
                $obj = $div.find('object, embed, img').filter(':first'),
                id   = this.id.match(/^post-([0-9]+)$/);

        if( $obj.size() > 0){
                // Find parent
                var $par = $obj.closest('p');


                // Move to top of div
                $obj.prependTo($div);

                // Remove the now empty parent
                $par.remove();

                if( $obj.is('img')){
                        // You can't wrap objects and embeds with links, so make sure we just wrap images
                        $obj.wrap( $j('<a></a>').attr('href', '/blog/?p='+id[1]));
                }
        }

        // Wrap the contents of the h2, not the h2 itself, with a link
        $h2.wrapInner( $j('<a></a>').attr('href', '/blog/?p='+id[1]) );
     $div.children( ('p:eq(0)').substring(0,100));
     $div.children('p:gt(0)').remove();

});
+1  A: 

This should work:

$fC = $div.children("p:first-child");
$fC.html($fC.html().substring(0,100));

tested: it works for me. my mock code: http://pastebin.com/f737f7ce9

thephpdeveloper
+1  A: 
$div.children( ('p:eq(0)').substring(0,100));

Look at that line. It's taking the first 100 characters of "p:eq(0)" and using that as a selector for the children. The first 100 characters will just be itself, so no trunction. thephpdeveloper is right, you want the innerHTML. Except, if the paragraph has HTML as contents you don't want to split a tag. So use text instead.

var truncatedText = $div.children('p').eq(0).text().substring(0, 100);
$div.empty().append(jQuery("<div/>").text(truncatedText));

Also, why do all your variables start with $? That's normally reserved for important system-level variables.

darkporter
A: 

you could replace the "$" with "jQuery" in your code and it'll work just fine.. i think

pkanane