最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add html tags to every letter in a string - Stack Overflow

programmeradmin1浏览0评论

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!

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!

Share Improve this question asked May 6, 2014 at 7:18 user3104155user3104155 2373 silver badges7 bronze badges 1
  • It seems you forgot to post jQuery code. – Satpal Commented May 6, 2014 at 7:20
Add a comment  | 

7 Answers 7

Reset to default 5

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

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.

HTML Code

<div id="str">hello</div>
<div id="result">

</div>

JS Code

$(function(){
    var str= $('div#str').html();
    for(var i=0; i<str.length; i++){
        $('div#result').append('<span>'+str[i]+'</span>');
    }
});

Try,

var xDiv = $('div');
var xChars = $.trim(xDiv.text()).split('');
xDiv.empty();

$.each(xChars,function(i,val){
  xDiv.append($('<span>'+ val +'</span>'));
});

You could also do this with a regex:

//var s = 'hello';
var s = $('#myDiv').html(); // get the string from the div

var newStr = s.replace(/(.)/gi, function(str, g1) {
    return '<span>' + g1 + '</span>';
});

alert(newStr);

Here is a JSfiddle demoing one way to do this.

  1. Select text
  2. Split text into an Array of letters
  3. Iterate over the Array and append to target element

Jquery

// For all matching elements
$(string).each(function() {

    // Get contents of string
    var myStr = $(this).html();

    // Split myStr into an array of characters
    myStr = myStr.split("");

    // Append strings to the result div in spans
    for (var i = 0, len = myStr.length; i < len; i++) {
        $("#result").append("<span>"  + myStr[i] + "</span>");
    }
});

Html output

<div id="letters">hello world</div>

<div id="result">
  <span>h</span>
  <span>e</span>
  <span>l</span>
  <span>l</span>
  <span>o</span>
  <span> </span>
  <span>w</span>
  <span>o</span>
  <span>r</span>
  <span>l</span>
  <span>d</span>
</div>
var txt = $("div").text();
var html = [];
for(var i in txt) html.push("<span>" + txt[i] + "</span>");
$("div").html(html.join(""));

I wouldn't use html() or append() with every character. This will force the browser to re-calc with every call. It's better to build your content and update when ready.

发布评论

评论列表(0)

  1. 暂无评论