Reputation: 2573
I'm trying to wrap each number in a span.
Here is where I'm at.
<div class="numbers">12345</div>
<div class="numbers">12345</div>
<div class="numbers">12345</div>
$('.numbers').each(function (index) {
var characters = $(this).text().split("");
$(this).empty();
$.each(characters, function (i, el) {
$(this).append("<span>" + el + "</span");
});
});
Where could I be going wrong with the syntax?
Upvotes: 6
Views: 15055
Reputation: 207501
this
is not what you think it is here
$(this).append("<span>" + el + "</span");
adding a console line shows you what this
is
console.log(this); //String {0: "1", length: 1}
You need to get the this from the outside scope, Store it in a variable and reference it.
var elem = $(this);
var characters = elem.text().split("");
elem.empty();
$.each(characters, function (i, el) {
elem.append("<span>" + el + "</span");
});
Upvotes: 2
Reputation: 388316
You can use a simple regex like
$('.numbers').html(function (i, html) {
return html.replace(/(\d)/g, '<span>$1</span>');
});
Demo: Fiddle
Or
$('.numbers').html(function (i, html) {
var chars = $.trim(html).split("");
return '<span>' + chars.join('</span><span>') + '</span>';
});
Demo: Fiddle
Upvotes: 13
Reputation: 97672
this
in the $.each
is not the same in the this
in $('.numbers').each
so you'll have to save it to a variable to use it there.
$this = $(this);
$this.empty();
$.each(characters, function (i, el) {
$this.append("<span>" + el + "</span");
});
Upvotes: 4