JSFiddle - React, Tailwind, and code Playground
by Yair Even Or
HTML
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p><span>1<b>2</b>3</span></p>
<p></p>
<p></p>
<p></p>
<p></p>
<p></p>
JavaScript
// elemetns to modify their attributes
var elms = document.querySelectorAll('p');
for( var i = elms.length; i--; ){
var attrs = {
contenteditable : '',
class:'my_class',
// html : 'testing',
styles:{
backgroundColor:'lightblue',
color:'darkred'
},
};
setAttributes(elms[i], attrs);
}
// sets attributes without touching the DOM itself for every change
// by closing the node, changing things and replaceing the original one.
function setAttributes(elm, attrs){
var parent = elm.parentNode,
cloned = elm.cloneNode(true); // deep clone
// change the cloned node
for (var idx in attrs){
if ((idx === 'styles' || idx === 'style') && typeof attrs[idx] === 'object')
for (var prop in attrs[idx]){cloned.style[prop] = attrs[idx][prop];}
else if (idx === 'html')
cloned.innerHTML = attrs[idx];
else
cloned.setAttribute(idx, attrs[idx]);
}
// replace the elmenet with the modified clone
parent.replaceChild(cloned, elm);
}