I'm building kind of a mini block editor for my Wordpress blog on frontend, where I'm trying to use javascript to convert all elements from post content to a set of inputs and textareas.
At first I create a dummy element and add post content from php to it:
var dummy = document.createElement( 'div' );
dummy.innerHTML = '<?php echo $text; ?>';
console.log(dummy.innerHTML);
Then foreach element there I run this kind of replacer, which should add the inputs and textareas on the place of element and remove the element itself.
var els = dummy.childNodes;
for(i = 0; i < els.length; i++) {
var text = els[i].textContent;
if (els[i].tagName.toLowerCase() == ("h2" || "h3" || "h4" || "h5" || "h6")) {
// Create an input
var input = document.createElement("input");
input.type = "text";
input.value = text;
input.setAttribute("class","h");
els[i].parentNode.insertBefore(input, els[i]);
} else if (els[i].tagName.toLowerCase() == ("p" || "div")) {
// Create a textarea
var textarea = document.createElement("textarea");
textarea.value = text;
textarea.setAttribute("class","p");
els[i].parentNode.insertBefore(textarea, els[i]);
} else if (els[i].tagName.toLowerCase() == "li") {
// Create an input with class li
var input = document.createElement("input");
input.type = "text";
input.value = text;
input.setAttribute("class","li");
els[i].parentNode.insertBefore(input, els[i]);
}
els[i].parentNode.removeChild(els[i]);
}
In the end I check the result and add it to my container. However, the results confuse me:
- h3 dissappears completely
- divs and p are there
- no inputs or textarea in the result
- no errors in console
console.log(dummy.innerHTML);
document.getElementsByClassName('compositecontent')[0].innerHTML = dummy.innerHTML;