12345

Wrap each character in the gap

I try to wrap every number in between.

That is where I am.

<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 can I get the syntax wrong?

0
source share
3 answers

thisin $.eachdoes not match thisin $('.numbers').each, so you will need to store it in a variable in order to use it there.

$this = $(this);
$this.empty();
$.each(characters, function (i, el) {
    $this.append("<span>" + el + "</span");
});

http://jsfiddle.net/phA8q/

+2
source

You can use a simple regular expression 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

+6
source

this , .

$(this).append("<span>" + el + "</span"); 

, this

console.log(this); //String {0: "1", length: 1} 

, .

var elem = $(this);
var characters = elem.text().split("");
elem.empty();

$.each(characters, function (i, el) {
    elem.append("<span>" + el + "</span");
});
0

Source: https://habr.com/ru/post/1663591/


All Articles