HTML:
<div id="test">Testing
<p>Some more text inside p</p>
<p>asdasdasdasdasde p</p>
Test
</div>
JAVASCRIPT:
getTextNodes(document.getElementById("test" ), 'strong');
function getTextNodes(parent, tag)
{
var textNodes = [];
var nodes = parent.childNodes;
for(var i=0;i<nodes.length;i++)
{
(function(i){
var node = nodes[i];
if(node.nodeType === 3)
{
textNodes.push(node);
if(node.data.match(/[^\t\r\n ]/))
{
var words = node.nodeValue.split(' ');
console.log(node);
var nWords = [];
for(var y = 0; y < words.length; y++)
{
(function(y){
var w = words[y];
if(w.trim() == ''){return;}
var nNode = document.createTextNode('');
nNode.nodeValue += w + ' ';
var bold = document.createElement(tag);
bold.appendChild(nNode);
parent.insertBefore(bold, node);
})(y);
}
parent.removeChild(node);
}
}
else
{
getTextNodes(node, tag);
}
})(i);
}
}
这是工作代码:http://jsfiddle.net/dnjsY/48/
我将每个单词用空格分隔,但事实是它用<strong>
标签双重包装一些文本节点,但不是第一个像"some"
单词的文本节点,有人可以给我一个提示,什么是错的?感谢
答案 0 :(得分:0)
http://jsfiddle.net/dnjsY/59/ - 解决方案
getTextNodes(document.getElementById("test" ), 'strong');
function getTextNodes(parent, tag)
{
var nodes = parent.childNodes;
for(let i=0;i<nodes.length;i++)
{
var node = nodes[i];
if(node.nodeType === 3)
{
if(node.data.match(/[^\t\r\n ]/))
{
var words = node.nodeValue.split(' ');
var stop = false;
var nWords = [];
for(let y = 0; y < words.length; y++)
{
var w = words[y];
if(w.trim() == ''){continue;}
var nNode = document.createTextNode('');
nNode.nodeValue = w + ' ';
var bold = document.createElement(tag);
bold.innerHTML = w + ' ';
parent.insertBefore(bold, node);
if(y == 1 && i == 0)
{
stop = true;
}
}
parent.removeChild(node);
if(stop)
{
return;
}
}
}
else
{
getTextNodes(node, tag);
}
}
}