Shonna
Shonna

Reputation: 1133

How to select text after an element with jquery?

I have a paragraph:

<p>red orange yellow green blue indigo violet</p>

I need to wrap the ending text in something that I can hide/show on click, like so:

<p>red orange yellow green 
  <a href="#">...Show More</a>
  <span="unhideme">blue indigo violet</span>
</p>

This is how far i've gotten:

<p>red orange yellow green 
  <a href="#">...Show More</a> 
  blue indigo violet
</p>

Is there some way to say "select all text after the a tag and wrap it in a span" with jquery? Or some other solution to generating a "Read More" button with jquery?

Upvotes: 0

Views: 110

Answers (2)

zgood
zgood

Reputation: 12571

This maybe a start:

$('p').each(function () {
    var $p = $(this);
    var words = $p.html().split(' ');
    $p.html('');

    for (var i = 0; i < 3; i++) {
        $p.append(words[i] + ' ');
    }

    if (words.length > 3) {
        var htmlStr = '<a href="#">...Show More</a><span class="unhideme">';
        for (var i = 3; i < words.length; i++) {
            htmlStr += words[i] + ' ';
        }
        htmlStr += '</span>';

        $p.append(htmlStr);
    }
}); 

$('p').on('click', 'a', function () {
     $(this).hide().next().show();
}); 

That 3 is hard-coded so you may want to change that. It basically represents how many items you want shown.

OR

If you want a plug-in to do all the dirty work for you check out trunk8 for jquery.

Upvotes: 0

Kierchon
Kierchon

Reputation: 2289

Just parse through the HTML of the p tag. Start by getting it all then breaking it up then just append the a and span tags before making it the HTML again.

var allText = $("p").html();
var firstHalf = allText.substring(0,INDEX AT WHICH YOU WOULD LIKE TO STOP);
var secondHalf = allText.substring(INDEX AT WHICH YOU WOULD LIKE TO STOP+1);
var newHTML = firstHalf + '<a href="#">...Show More</a><span class="unhideme">' + secondhalf + "</span>";

$("p").html(newHTML);

Upvotes: 1

Related Questions