Many may ask why in the desire to see if it’s really needed. While undesirable it is for this particular use case which won’t detail since not relevant to the answer. It’s easily accomplished with a line of JQuery but alas needs to be plain js and ideally as short and straightforward as possible. See similar requests on SO but many for moving inside a div or with slightly more complex requirements.
Created a basic example that works as desired:
var contentDiv = document.querySelector('.c');
var anchorDiv = document.querySelector('.b');
contentDiv.after(anchorDiv);
<div class="container">
<div class="a">
A
</div>
<div class="b">
B
</div>
<div class="c">
C
</div>
</div>
When doing it on the real code however get the error:
TypeError: null is not an object (evaluating 'contentDiv.after')
While having the script at the top of the page can cause that, have it at the bottom, so is there anything else that might be causing that?
The actual code using is the following incase the specific class names are problematic?:
<script>
var contentDiv = document.querySelector('.product-description');
var anchorDiv = document.querySelector('.product-details__container');
contentDiv.after(anchorDiv);
</script>
Also thought maybe I need a document ready on that. So did:
<script>
document.addEventListener('DOMContentLoaded', function () {
var contentDiv = document.querySelector('.product-description');
var anchorDiv = document.querySelector('.product-details__container');
contentDiv.after(anchorDiv);
}, false);
</script>
But same error. Any ideas?
If you AJAX some of the page, you many not HAVE that element with that class at the time the code runs
Try this to see if it eventually works, then you know why
const swap = () => {
const contentDiv = document.querySelector('.product-description');
const anchorDiv = document.querySelector('.product-details__container');
if (contentDiv && anchorDiv) contentDiv.after(anchorDiv);
else {
console.log({contentDiv},{anchorDiv})
setTimeout(swap,1000)
}
};
window.addEventListener('load', swap);