Adrian Florescu
Adrian Florescu

Reputation: 4502

jQuery - Select second word and warp the text

I have a menu list like this:

<ul>
<li class="but"><a href="#">ONE WORD<small>Other words here</small></a></li>
<li class="but"><a href="#">ONE WORD<small>Other words here</small></a></li>
<li class="but"><a href="#">ONE WORD<small>Other words here</small></a></li>
<li class="but"><a href="#">ONE WORD<small>Other words here</small></a></li>
</ul>

How can I automatically select the second word from li.but and warp it into a span like this:

<ul>
<li class="but"><a href="#">ONE <span>WORD<span><small>Other words here</small></a></li>
<li class="but"><a href="#">ONE <span>WORD<span><small>Other words here</small></a></li>
<li class="but"><a href="#">ONE <span>WORD<span><small>Other words here</small></a></li>
<li class="but"><a href="#">ONE <span>WORD<span><small>Other words here</small></a></li>
</ul>

Thank you very much!

Upvotes: 1

Views: 3032

Answers (5)

Joe Ng&#39;ethe
Joe Ng&#39;ethe

Reputation: 870

Below is a code for wrapping the second word in a span with a class. Maybe you can adopt it. do something like this;

$('.list-item a').each(function(){ var text = $(this).text().split(' '); if(text.length < 2) return; text[1] = '<span class="color-red">'+text[1]+'</span>'; $(this).html( text.join(' ') ); });

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359906

Something like this:

$('ul > li.but > a').html(function (i, oldHtml)
{
    return oldHtml.replace(/(\s)(\w+)/, '$1<span>$2</span>');
});

Demo: http://jsfiddle.net/mattball/ptUuS/

Upvotes: 3

Šime Vidas
Šime Vidas

Reputation: 185933

Here you go:

$('li.but > a').html(function(i, v) {
    return v.replace(/\s(.*?)\s/, ' <span>$1</span> ');
});

Live demo: http://jsfiddle.net/simevidas/6dkAy/3/

Upvotes: 7

neeebzz
neeebzz

Reputation: 11538

Here you go

$("ul > li > a").each(function(index, el) {

   var sec = $(this).html().split(" ");
   sec = sec[1].split("<")[0];
   var total = "<span>" + sec + "</span>";

   var html = $("ul > li > a").html();
   html = html.replace(sec, total);
   $(this).html(html);
});

Upvotes: 1

Emre Erkan
Emre Erkan

Reputation: 8482

Here:

$('.but a').each(function() {
   var $a = $(this);
   var $small = $a.find('small');
   var smallText = $small.html();
   $small.remove();
   var arr = $a.html().split(' ');
   arr[1] = ['<span>', arr[1], '</span>'].join('');
   $a.html(arr.join(' ')).append(['<small>', smallText, '</small>'].join(''));
});

jsFiddle

Upvotes: 1

Related Questions