Equivalent to javascript wrap

Asked

Viewed 307 times

1

The jquery has a method called wrap that basically adds a container to the desired element, but I can’t find the javascript method, anyone knows?

3 answers

1

Well, I think maybe this 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

Reference links for study:

  • I appreciate the help, but I was looking for something like wrap, where you pass the whole html code without concatenation.

0

Something like that 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>

0


Unfortunately I did not find anywhere an equivalent function, where you pass an element and an html string as container, so I made my own, is working perfectly, I will leave here for future references.

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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.