Skip to content Skip to sidebar Skip to footer

Put Each Letter In Given Div In Separate Span

The following div contains some text and tags. I want to add tag to every letter in the div.
Hello, John<

Solution 1:

I've (very recently) been in your shoes, not even knowing where to start. The magic words are "JavaScript DOM manipulation":

var text = document.getElementById("text");
varstring = "Hello, John";
string.split("");
var i = 0, length = string.length;
for (i; i < length; i++) {
    text.innerHTML += "<span>" + string[i] + "</span>";
}

That just puts them all in spans. You should try giving it a try to get the <span class="name"> bit working on your own from here.

Solution 2:

You can try something like this: http://jqversion.com/#!/LKQqeGh (with jQuery)

var $div = $('#text').clone().html('');
$('#text').contents().each(function(){
  var spanClass = '';

  if ($(this).is('span')) {
    spanClass = $(this).attr('class');
  }

  $textArray = $(this).text().split('');

  for (var i = 0; i < $textArray.length; i++) {
    $('<span>').addClass(spanClass).text($textArray[i]).appendTo($div);
  }
});

$('#text').replaceWith($div);

Solution 3:

HTML :

<divid="text">Hello, <spanclass="name">John</span></div>

Pure Javascript :

var text = document.getElementById("text");
var msg = text.textContent;
var name = document.getElementsByClassName("name")[0].textContent;

// remove name from msg
msg = msg.substring(0,msg.length - name.length);
// to char array
msg = msg.split('');
name = name.split('');

text.innerHTML = "<span>" + msg.join("</span><span>") + "</span>";
text.innerHTML += "<span class=\"name\">" + name.join("</span><span class=\"name\">") + "</span>";

Demo JSFiddle

Post a Comment for "Put Each Letter In Given Div In Separate Span"