How do I wrap a span around the last word of an element's inner text, using jQuery?
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 ap开发者_Go百科preciated
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(''));
});
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(' '));
});
Hmm, this isn't particularly easy. The most orthodox way to do this is with 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.
精彩评论