Full-time web dev; JS lover since 2002; CSS fanatic. #CSSIsAwesome
I try to stay up with new web platform features. Web feature you don't understand? Tell me! I'll write an article!
He/him
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.
So off the top, I don't think you can replace the
<html>
tag itself; when I try using stuff likehtmlElement.outerHTML = '...'
, I get errors like: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 usehtmlElement = document.getRootNode().firstElementChild
to get the<html>
tag, then sethtmlElement.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.Thanks this definitely the type of approach I had in mind but couldn't quite wrap my head around it in this way.