Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unwrap element without jQuery and using createElement

Tags:

javascript

With jQuery it's really easy unwrap elements but with pure JS it's not that easy. I spent the last 2 hours trying but no result. I read ALL the topics on Google and SO and no solution. Most of them use jQuery, others are not cross browsing.

So far I have:

    var temp = document.createElement("div");
    temp.innerHTML = "HERE COMES A COMPLEX HTML WITH SEVERAL DIVS, SPANS...";
    document.insertNode(temp);

The problem is that my HTML code is being inserted with the "div" surrounding it. I need to remove this div from being parent. I made an attempt that maybe is a clue but so far not helping:

Instead of:

document.insertNode(temp);

I use

document.insertNode(temp.firstChild);

The problem is that only the firstChild is being inserted in the document.

You may say it is useless what I need but it's not! I have a website which (as you can see) is veeery loaded, full of css effects and as you scroll down the page it gets more loaded and loaded. If I could unwrap this outer div it would be great since I will insert at least 120 commponents in the website.

I am optimizing this websit traffic to balance it, so I will make it all script. There will be minimal html. All the images and remaining divs will be inserted using this method, so at the end I will not want 120 useless divs in the DOM that could have been removed. I have my reasons so I am here not to discuss the why, but I need to unwrap the div.

OBS: there is method that is using outerHTML = innerHTML but it repaints all the page everytime it's called. So it's a terrible idea.

like image 290
amandanovaes Avatar asked Dec 05 '25 05:12

amandanovaes


1 Answers

In case somebody’s still interested, it’s possible to get all element’s contents with Range.selectNodeContents(), then extract into a DocumentFragment with Range.extractContents(). After that, nothing stops you from using ParentNode.replaceChild, as DocumentFragment is an ordinary Node.

Not sure about performance, but at least there’re no individual nodes being extracted and inserted, should be pretty fast.

like image 81
K Lee Avatar answered Dec 07 '25 19:12

K Lee