I have a string of letters within a div - such as this...
<div>hello</div>
I'd like to add a html tag to each letter in the string so it will be - such as this
<div>
<span>h</span>
<span>e</span>
<span>l</span>
<span>l</span>
<span>o</span>
</div>
Since the letters within this div will be dynamically changing it can't be static thus I'd like to use jquery to apply spans to every letter of the string.
Any help would be appreciated - thanks!
Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.
A few steps:
The code:
$('div').each(function() {
var letters = $(this).text().split(''),
$container = $(this).empty();
$.each(letters, function(_, letter) {
$('<span>', {text: letter}).appendTo($container);
});
});
Demo
You can just split the textContent then join it up again with suitable markup embedded. So presuming you have a reference to the div:
div.innerHTML = '<span>' + (div.textContent || div.innerText).split('').join('<\/span><span>') + '<\/span>';
There's always one kill–joy who points out the obvious flaw!! Ok, here's something more robust.
function spanizeText(element) {
var text = (element.textContent || element.innerText).split('');
element.innerHTML = '';
text.forEach(function(c) {
var sp = document.createElement('span');
sp.appendChild(document.createTextNode(c));
element.appendChild(sp);
});
}
It requires a polyfil for forEach in old browsers, or change forEach to a plain for loop (same number of lines of code, probably runs faster). It could be modified to accept a wrapper element that was setup with various attributes and properties that is cloned rather than use document.createElement.
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