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");
});
});
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With