The jquery
has a method called wrap
which basically adds a container to the desired element, but I can not find the method in javascript, does anyone know?
The jquery
has a method called wrap
which basically adds a container to the desired element, but I can not find the method in javascript, does anyone know?
Unfortunately I have not found an equivalent function anywhere, where you pass an element and a html string as a container, so I made my own, it's working perfectly, I'll leave it here for future reference.
function lastNode(el) {
if(el.children.length) return lastNode(el.children[el.children.length-1]);
else return el;
}
function wrap(string, el) {
creat = document.createElement('div');
creat.innerHTML = string;
parent = el.parentNode;
lastNode(creat).appendChild(el);
parent.appendChild(creat.firstChild);
}
let string = '<div id="e3"><div id="e4"></div></div>';
let el = document.querySelector('#e5');
wrap(string , el);
#e1 {
border: 5px black solid;
}
#e2 {
border: 5px orange solid;
}
#e3 {
border: 5px purple solid;
}
#e4 {
border: 5px green solid;
}
#e5 {
border: 5px red solid;
}
<div id="e1">
<div id="e2">
<div id="e5"></div>
</div>
</div>
Something like this would work:
function wrapHTML (element, wrapperElement) {
//Aqui você define seu wrapper
let wrapper = wrapperElement || document.createElement('div');
//Colocando um id só para evidenciar o wrapper.
wrapper.id = 'divFilha';
element.parentNode.appendChild(wrapper);
wrapper.appendChild(element);
return wrapper;
}
wrapHTML(document.getElementById('conteudoWrap'));
console.log(document.getElementById('divPai'));
<div id="divPai">
<input id="conteudoWrap" type="text" />
</div>