'Move div to be directly after another div with plain / native js? [closed]
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
