5

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?

uriah
  • 2,485
  • 5
  • 28
  • 40

3 Answers3

11

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
4

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/

Musa
  • 96,336
  • 17
  • 118
  • 137
2

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");
});
ashleedawg
  • 20,365
  • 9
  • 72
  • 105
epascarello
  • 204,599
  • 20
  • 195
  • 236