If I had a portion of html such as....
<html>
<head>
some code...
</head>
<body>
<header>
Some text
</header>
<section>
Some text
<div>
Some text
</div>
</section
</body>
</html>
Could I replace this portion of the HTML using JavaScript without any concern for elements or nesting or any particular element's innerHTML
etc?
<html>
<head>
some code...
</html>
<body>
<header>
Some text
</header>
<section>
Looking forward to hearing about some ways this could be done. Thanks!
Top comments (8)
I've read this a few times, and I'm not entirely sure what you're asking for, Ben. Can you clarify a bit? It looks like there's some malformed HTML in the first snippet, and incomplete HTML in the second.
Basically I want to replace the first half of the document, without concern for HTML elements or depth etc. Basically split the string in half and replace the first half with new HTML.
For some reason seems like a bad idea :)
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.
I'd suggest get the parent node using JS and then replace an entire node with another node that you've built.
Manipulating DOM by replacing
HTML
could be dangerous if any JS is depending on any part of that.Or use
oldChild.replaceWith(newChild)
You can replace parts of HTML either as string or by Dom manipulation and insert them back. But if you replace a node its children will be affected but not its siblings and parent. For example you can fetch the head part and manipulate it and insert it back. Same for header in your sample. I would recommend manipulating DoM rather than working with strings