DEV Community

Discussion on: How to replace arbitrary portions of HTML?

Collapse
 
kenbellows profile image
Ken Bellows

So off the top, I don't think you can replace the <html> tag itself; when I try using stuff like htmlElement.outerHTML = '...', I get errors like:

Uncaught DOMException: Failed to set the 'outerHTML' property on 'Element': This element's parent is of type '#document', which is not an element node.

But assuming your question could be rephrased to be about replacing the first half of the HTML inside the <html> tag, then sure, you can use htmlElement = document.getRootNode().firstElementChild to get the <html> tag, then set htmlElement.innerHTML to whatever you want and the browser will do its best to parse it. But there are more questions.

To write the code, I think you'd need to expand a bit more on what you want. Presumably this is meant to be a reusable bit of code, so what are the boundaries on what you'd be replacing? Like, on the probably-too-narrow end, sure, you could replace that exact string of HTML using something like htmlElement.innerHTML = html.innerHTML.replace('<head>...', '...new html here...'). But I'm assuming you want something more flexible, in which case you'd need to say more about how you find the start and end points of the segment to replace.

Collapse
 
ben profile image
Ben Halpern

Thanks this definitely the type of approach I had in mind but couldn't quite wrap my head around it in this way.