JSFiddle - React, Tailwind, and code Playground

by moob

HTML

<div data-placeholder="<div class='Google'><input type='text' value='abc'/></div>"></div>

<div data-placeholder="<div class='Boogle'><input type='text' value='def'/></div>"></div>

<div data-placeholder="<div class='Ooogle'><label>with label <input type='text' value='ghi'/></label></div>"></div>

<span data-placeholder="<em>Post JS</em>ddfds">Pre JS</span>
<br />
<button id="test">click me</button>

JavaScript

/* Use querySelectorAll to select all elements with the attribute 'data-placeholder' (returns a NodeList)*/

var placeholders = document.querySelectorAll('[data-placeholder]');

/* Extend the NodeList prototype with a simple 'each' method that allows us to iterate over the list. */

NodeList.prototype.each = function(func) {
    for (var i = 0; i < this.length; i++) {
        func(this[i]);
    }
    return this;//return self to maintain chainability
};

/* Extend the Object prototype with a 'replaceWith' method that replaces the element with a new one created from a html string: */

Object.prototype.replaceWith = function(htmlString) {
    var temp = document.createElement('div');//create a temporary element
        temp.innerHTML = htmlString;//set its innerHTML to htmlString
    var newChild = temp.childNodes[0];//(or temp.firstChild) get the inner nodes
        this.parentNode.replaceChild(newChild, this);//replace old node with new
    return this;//return self to maintain chainability
};

/* Put it all together: */
placeholders.each(function(self){
   self.replaceWith(self.dataset.placeholder);//the 'data-placeholder' string
});

/* Another example but here we only replace one specific element with some hard-coded html on click */
document.getElementById("test").addEventListener('click', function() {
   this.replaceWith("<strong>i was a button before</strong>");
}, false);