Swap My Html
by Sam Fereday
HTML
<div id="container">
<div class="test">
<div class="test-sub">
<p>
This is some text.
</p>
<ul>
<li>Option</li>
<li>Option</li>
<li>Option</li>
</ul>
</div>
</div>
</div>
<div id="output" data-ignore="ignore">
...
</div>
<button id="make">Let's do this</button>
CSS
body {
padding: 0;
font: 75%/1.4em arial;
}
#output {
padding: 1em;
background: #333;
color: #fff;
}
#output br:first-child {
display: none;
}
button {
margin-top: 1em;
}
#container {
display: none;
}
JavaScript
function swap(newelement, existing) {
if (existing.getAttribute("data-ignore") === "ignore")
return;
newelement.innerHTML = existing.innerHTML;
if (existing.className.length > 0)
newelement.className = existing.className;
if (existing.id.length > 0)
newelement.id = existing.id;
existing.parentNode.replaceChild(newelement, existing);
return newelement;
}
function getConversion(id, data) {
let c = data.find(function(item) {
return item.tag === id.toLowerCase();
});
console.log(c);
return c;
}
function makeFilthy(html, data) {
let con, elm;
for (var i = 0; i < html.length; i++) {
if (html[i].tagName) {
con = getConversion(html[i].tagName, data);
if (con && con.to)
elm = swap(document.createElement(con.to), html[i]);
if (con && elm && elm.childNodes.length > 0)
makeFilthy(elm.childNodes, data);
}
}
}
// Do your worst.
var conversions = [{
"tag": "div",
"to": "bastard"
}, {
"tag": "p",
"to": "sausage-fest"
}, {
"tag": "ul",
"to": "bellend"
}, {
"tag": "li",
"to": "fuck"
}];
// And make it so.
let container = document.getElementById("container");
let output = document.getElementById("output");
document.getElementById("make").addEventListener('click', function() {
makeFilthy(container.childNodes, conversions);
output.innerText = container.innerHTML;
});