JSFiddle - React, Tailwind, and code Playground
HTML
<div class="wrap">
<ul>
<li>This is</li>
<li>A list</li>
<li>And I want</li>
<li>This should not be bold</li>
<li>To wrap</li>
<li>This</li>
<li>strong</li>
<li>li</li>
</ul>
<span><p><em>This is another random tag</em></p></span>
</div>
JavaScript
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 container = document.querySelector('.wrap');
replacement(container.children, list);
/**
* Recursive function to replace all children.
*
* @param array containers The list of containers to loop through.
* @param array data The list of data to search and replace.
* @return void
*/
function replacement(containers, data){
console.log('Containers ::', containers);
console.log('Data ::', data);
if(!data || !data.length)
return;
for(let i=0; i<containers.length; i++){
var container = containers[i];
console.log('Container ::', container);
// Trigger the recursion on the childrens of the current container
if(container.children.length)
replacement(container.children, data);
// Perform the replacement on the actual container
for(let j=0; j<data.length; j++){
var index = container.textContent.indexOf(data[j].original);
// Data not found
if(index === -1)
continue;
// Remove the data from the list
var replace = data.splice(j, 1)[0];
container.innerHTML = container.innerHTML.replace(replace.original, '<strong>' + replace.new + '</strong>');
j--;
break;
}
}
}