Wrap equivalent in javascript

1

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?

    
asked by anonymous 20.11.2017 / 17:20

3 answers

0

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>
    
21.11.2017 / 03:13
1

Well, I think maybe that will help you.

org_html = document.getElementById("containerPAI").innerHTML;
new_html = "<div id='containerFILHO'>" + org_html + "</div>";
document.getElementById("containerPAI").innerHTML = new_html;

Good luck!

UPDATE

Study reference links:

20.11.2017 / 17:28
0

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>
    
20.11.2017 / 17:39