Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - How to wrap each character from a string in spans

How can I convert the characters of a div into spans?

For example, I'd like to convert this:

<div>
    Hello World
</div>

Into this:

<div>
    <span>H</span>
    <span>e</span>
    <span>l</span>
    <span>l</span>
    <span>o</span>
    <span>W</span>
    <span>o</span>
    <span>r</span>
    <span>l</span>
    <span>d</span>
</div>

I've tried this StackOverflow suggestion, but that converts spaces into spans. What I need is to convert only characters to spans:

$("div").each(function (index) {
    var characters = $(this).text().split("");

    $this = $(this);
    $this.empty();
    $.each(characters, function (i, el) {
        $this.append("<span>" + el + "</span");
    });
 });
like image 710
MoHamed HaSsn Avatar asked Dec 19 '22 11:12

MoHamed HaSsn


2 Answers

You can use String#replace method and html() method with a callback to reduce the code.

$("div").html(function(index, html) {
  return html.replace(/\S/g, '<span>$&</span>');
});

$("div").html(function(index, html) {
  return html.replace(/\S/g, '<span>$&</span>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  Hello World
</div>
like image 198
Pranav C Balan Avatar answered Jan 06 '23 15:01

Pranav C Balan


You can try with this simple JavaScript.

(function() {
  var div, i, span = "";
  div = document.querySelectorAll("div")[0];
  for (i = 0; i < div.innerText.length; i++) {
    if (div.innerText[i] !== " ") {
      span += "<span>";
      span += div.innerText[i];
      span += "</span>";
    }
  }
  div.innerHTML = span;
}());
<div>
  Hello World
</div>
like image 28
Danny Fardy Jhonston Bermúdez Avatar answered Jan 06 '23 16:01

Danny Fardy Jhonston Bermúdez