uriah
uriah

Reputation: 2573

Wrapping each character in a span

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

Answers (3)

epascarello
epascarello

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

Arun P Johny
Arun P Johny

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

Musa
Musa

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");
});

http://jsfiddle.net/phA8q/

Upvotes: 4

Related Questions