How to wrap scrolling around the last word of an element’s inner text using jQuery?

I know that this should be a simple task, but I am having problems choosing the title element of the last word and moving it in between so that I can add style changes.

That's what i still have

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

Any help would be greatly appreciated.

+5
source share
3 answers

, jQuery DOM. DOM node, , . , jQuery. :

$('.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(''));
});
+15

:

$('.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(' '));
});
+2

Hmm, this is not particularly easy. The most orthodox way to do this is DOMNode.splitText:

$('.side-c h3').each(function(){
    var oldNode = this.firstChild,
        newNode = oldNode.splitText(oldNode.data.lastIndexOf(' ') + 1), // don't wrap the space
        span = document.createElement('span');

    this.replaceChild(span, newNode);
    span.appendChild(newNode);
});

See jsfiddle .

0
source

All Articles