See comments:
// Get the `.something` element and its parent
const something = document.querySelector(".something");
const parent = something.parentElement;
// Get the `navbar` inside it and move it in front of it
const navbar = something.querySelector(".navbar");
parent.insertBefore(navbar, something);
// Get the `footer` inside it and insert it after it
const footer = something.querySelector("footer");
parent.insertBefore(footer, something.nextElementSibling);
<div class="something">
<nav class="navbar"></nav>
<footer></footer>
</div>
After that runs, if you right-click the output pane and look at the HTML, you'll see they're in the requested order (ignore the script
that the snippet puts there).
If you have this repeated on a page, all you have to change is how you get the something
elements to work on, using a loop:
for (const something of document.querySelectorAll(".something")) {
// ...rest of the code goes here unchanged...
}
Note that that requires that the NodeList
from querySelectorAll
is iterable, which it is in modern environments. You can polyfill that for slightly older environments that support iteration but hadn't yet made NodeList
iterable as I describe in this answer. For environments that don't support iterability, that link also shows how to polyfill forEach
if NodeList
doesn't have it, which you'd use like this:
document.querySelectorAll(".something").forEach(something => {
// ...rest of the code goes here unchanged...
});