Reputation: 65
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
Reputation: 178421
How about this - assuming only two words:
$('.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
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
Reputation: 388446
Try
$('.dateCalendar').html(function(i, v) {
return $.trim(v).replace(/(\w+)/g, '<span>$1</span>');
});
Demo: Fiddle
Upvotes: 4