Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wrap a span around the last word of an element's inner text, using jQuery?

Tags:

html

jquery

text

I know this should be a simple task but I'm having problems selecting a heading elements last word and wrapping that in a span so I can add style changes.

Here's what I have so far

$('.side-c h3').split(/\s+/).pop().wrap('<span />');

Any help would be greatly appreciated

like image 696
Seán O'Grady Avatar asked Feb 09 '11 21:02

Seán O'Grady


2 Answers

The problem is that jQuery objects wrap DOM nodes. Each word in the element is not a DOM node itself, so you'll need a little more work to break apart the text and rejoin it. You also need to account for multiple nodes being selected by jQuery. Try this:

$('.side-c h3').each(function(index, element) {
    var heading = $(element), word_array, last_word, first_part;

    word_array = heading.html().split(/\s+/); // split on spaces
    last_word = word_array.pop();             // pop the last word
    first_part = word_array.join(' ');        // rejoin the first words together

    heading.html([first_part, ' <span>', last_word, '</span>'].join(''));
});
like image 157
Stephen Avatar answered Sep 20 '22 14:09

Stephen


This does it:

$('.side-c h3').each(function(){
   var $this = $(this), text=$this.text().trim(), words = text.split(/\s+/);
   var lastWord = words.pop();
   words.push('<span>' + lastWord + '</span>');
   $this.html(words.join(' '));
});
like image 45
Neil Avatar answered Sep 21 '22 14:09

Neil