Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping each character in a span

Tags:

jquery

syntax

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?

like image 577
uriah Avatar asked Feb 20 '14 02:02

uriah


3 Answers

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

like image 163
Arun P Johny Avatar answered Oct 31 '22 11:10

Arun P Johny


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/

like image 4
Musa Avatar answered Oct 31 '22 12:10

Musa


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");
});
like image 2
epascarello Avatar answered Oct 31 '22 10:10

epascarello