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?
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
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");
});
http://jsfiddle.net/phA8q/
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");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With