Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add html tags to every letter in a string

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!

like image 618
user3104155 Avatar asked May 06 '14 07:05

user3104155


People also ask

How do you add a tag to a string in HTML?

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.


2 Answers

A few steps:

  1. Grab the text contents and create an array of individual characters,
  2. Empty the original container,
  3. Add each letter as a span element.

The code:

$('div').each(function() {
    var letters = $(this).text().split(''),
    $container = $(this).empty();

    $.each(letters, function(_, letter) {
       $('<span>', {text: letter}).appendTo($container);
    });
});

Demo

like image 54
Ja͢ck Avatar answered Sep 24 '22 16:09

Ja͢ck


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>';

Edit

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.

like image 22
RobG Avatar answered Sep 24 '22 16:09

RobG