VI_au VI_au - 19 days ago 13
jQuery Question

jQuery - if div has two words, strike through first word

I have a piece of jQuery which looks at a div, and strikes through the first word. This works fine, however if that div only has one word I dont want it to strike through.

Anyone know how to achieve this?

Code:

jQuery('.class').each(function(index) {

//get the first word
var firstWord = $(this).text().split(' ')[0];

//wrap it with strike
var replaceWord = "<strike>" + firstWord + "</strike>";

//create new string with span included
var newString = $(this).html().replace(firstWord, replaceWord);

//apply to the divs
jQuery(this).html(newString);
});

Answer
jQuery('.class').each(function(index) {

// get the word array
var words = $(this).text().split(' ')

if ( words.length === 1 ) {
    // nothing to see here
    }
else  
    {
    //get the first word
    var firstWord = $(this).text().split(' ')[0];

    //wrap it with strike
    var replaceWord = "<strike>" + firstWord + "</strike>";

    //create new string with span included
    var newString = $(this).html().replace(firstWord, replaceWord);

    //apply to the divs
    jQuery(this).html(newString);
    }

});
Comments