如何在文本段落中的每一个单词上添加跨度

How to add spans to every word in paragraph of text?

本文关键字:单词 添加 每一个 文本 段落中      更新时间:2023-09-26

如何将span附加到特定文档div("text")中的每个单词?在js中使用nodes的新手。不断收到消息,

"对象没有方法追加子对象…"

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

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); 
    }
}

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

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

然后将单词附加到

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