Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
Move div to be directly after another div with plain / native js?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!