For A Shadier Tomorrow

Wrap nth Word Using jQuery

Wrapping nth word from specific target element is very simple task. Today we will learn how to do it using jQuery.

For example purpose, Let’s say that we want to wrap the second word from all .widget-title with span tag. Then here’s how we do it:

$('.widget-title').each(function(){

    var text = $(this).text().split(' ');
    var n = 1; // specify which word we're wrapping. remember that the count starts from 0
    var t = 'span'; // which HTML tag are we going to use as wrapper?
    
    if(n>=text.length){return;}

    text[n] = '<'+t+'>'+text[n]+'</'+t+'>';

    $(this).html( text.join(' ') );

});

You just need to make change to the 4th and 5th line.

The 4th line specifies the n word we’re targeting.
Remember that programmers are a bit different compared to ordinary human. Their counting starts from 0 instead of 1.

The 5th line is just as simple. you just need to determine the tag used as wrapper.

The 7th line are there just in case the n number specified in the 4th line went over the total number of words the target has. Without this line, you could get a lot of undefined outputs.

See the Pen Wrap nth Word Using jQuery by Abdul Azis (@ShadyThemes) on CodePen.


That’s all. Very easy, don’cha think?

Hope this trick could be useful for you. Oyasumi~~

Write a comment

Your email address will not be published. Required fields are marked *

About ShadyThemes

ShadyThemes is a shady group for hire.

We build shady websites using shady tools for whatever shady purpose the shady clients has in their shady mind.

As you may have guessed, everything you see around ShadyThemes website is coded by us, so I guess you can see them as our portfolios.

Just send us a message if you need our service.

Contact Form

Eroges are dangerous! They're better than reality!!