- node node.
( ) , Zsolt V, .
Zsolt V , innerHTML HTML. , , , node Node, , DOM ( DOM) textContent .
var list = [{
original: 'This is',
new: 'New this is'
}, {
original: 'A list',
new: 'New A list'
}, {
original: 'And I want',
new: 'New And I want'
}, {
original: 'To wrap',
new: 'New To wrap'
}, {
original: 'li',
new: 'bold'
}, {
original: 'This',
new: 'New This'
}, {
original: 'strong',
new: 'bold'
}, {
original: 'This is another random tag',
new: 'This is another random tag that should be bold'
}
];
var div = document.getElementsByClassName("wrap")[0];
function processNode(node) {
if (node.nodeName === "#text") {
list.forEach(function(item, index) {
if (node.parentNode && node.textContent.indexOf(item.original) > -1) {
let untouched = node.textContent.split(item.original);
console.log(untouched);
for (let i = untouched.length - 1; i > 0; i--) {
untouched.splice(i, 0, item.new);
}
console.log(untouched);
for (let i = 0, l = untouched.length; i < l; i++) {
let newNode = i % 2 === 0 ? document.createTextNode("") : document.createElement("strong");
newNode.textContent = untouched[i];
node.parentNode.appendChild(newNode);
}
node.parentNode.removeChild(node);
}
})
} else {
node.childNodes.forEach(function(child, index) {
processNode(child);
})
}
}
processNode(div)
JSFiddle ( )
Zsolt V , :
, , ,
, list. , , , .. list[7], list[0]:
" " (list[7] before)
-> " New is another random tag" ( list[7]after making changes from list[0])
You must remember about the order.
In fact, I moved the last element to the array listat the top, and the results were the same as you requested.
var list = [{
original: 'This is another random tag',
new: 'This is another random tag that should be bold'
}, {
original: 'This is',
new: 'New this is'
}, {
original: 'A list',
new: 'New A list'
}, {
original: 'And I want',
new: 'New And I want'
}, {
original: 'To wrap',
new: 'New To wrap'
}, {
original: 'li',
new: 'bold'
}, {
original: 'This',
new: 'New This'
}, {
original: 'strong',
new: 'bold'
}
];
JSFiddle (full answer)