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
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(' '));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With