如何为文本段落中的每个单词添加跨度?

时间:2014-04-10 05:45:26

标签: javascript append nodes html

如何将跨度附加到特定文档div(“文本”)中的每个单词?在nodes中使用js的新功能。继续收到消息,

  

“对象没有方法追加孩子......”

我错过了什么?这是我的代码:

var y; 
var words; 

function get() {
    y = document.getElementById("text").firstChild.nodeValue;  

    words = y.split(" "); 

    for (var x = 0; x < 3; x++)
    {
        var newSpan = document.createElement('span'); 
        words[x].appendChild(newSpan); 

    }
}

1 个答案:

答案 0 :(得分:0)

您需要先获取要附加单词的dom元素,

elem = documents.getElementById("#some_container");

然后将单词附加到它

words.forEach(function(w) { 
 var new_span = document.createElement('<span>');
 new_span.innerHTML = w;
 elem.appendChild(new_span);
});
相关问题