Kelly Kruschel
Kelly Kruschel

Reputation: 65

Wrap first and second word in two different spans with jQuery

I have tried two other suggestions found here to put a span around a word but each time it resulted in the span appearing above the text and not around it.

I have the following code:

<div class="dateCalendar">
June 10
</div>

The jQuery I am currently using is:

$('.dateCalendar').html(function(i, v) { return v.replace(/\s(.*?)\s/, ' $1 '); });

The HTML output is showing this:

<div class="dateCalendar">
<span></span>
June 10
</div>

Ideally in the end I would like to wrap the month in a span and the date in another span so I can style them differently in css.

Some notes that may be helpful to know:

Upvotes: 4

Views: 1411

Answers (3)

mplungjan
mplungjan

Reputation: 178421

How about this - assuming only two words:

Live Demo

$('.dateCalendar').each(function () {
  var cal = $(this); 
  var texts = $(this).text().split(" ");
  cal.empty();                   
  $.each(texts,function (i, text) {
    cal.append('<span class="' + (i == 0 ? "month" : "year") + '" >'+text+'</span>');
  });
});

Upvotes: 1

Kevin Sj&#246;berg
Kevin Sj&#246;berg

Reputation: 2254

You're almost there. The reason it's failing is because the resulting content isn't wrapped inside any tag.

See http://jsfiddle.net/ZymGK/1/. Basically this returns an array of span elements for each "word" (delimited by spaces) and make that the content of each div element with the class .dateCalendar.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

Try

$('.dateCalendar').html(function(i, v) { 
    return $.trim(v).replace(/(\w+)/g, '<span>$1</span>'); 
});

Demo: Fiddle

Upvotes: 4

Related Questions