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

161
Views
jQuery change order of children anchors after each div

I have a div with children elements that currently looks something like this

    <div>
    <div class="div-el"></div>
    <a href="#">Anchor</a>
    <div class="div-el"></div>
    <a href="#">Anchor</a>
    <a href="#">Anchor</a>
    <a href="#">Anchor</a>
    <div class="div-el"></div>
    </div>

Here's what I am trying to achieve

    <div>
    <div class="div-el"></div>
    <a href="#">Anchor</a>
    <a class="empty">Anchor</a>
    <div class="div-el"></div>
    <a href="#">Anchor</a>
    <a href="#">Anchor</a>
    </div>

So I am trying to make it so that

  1. There's at least 2 anchor elements next to each child .div-el element.
  2. In case if there's only one <a> element before the beginning of another .div-el element, add a blank <a> element like <a class="empty"></a>

Edit: I have been on it for hours and one of the things I have tried is the following with failure:

$('div > a').each(function(){
    var nextPromo = $(this).next();
    var prevPromo = $(this).prev();
    if (nextPromo.attr('href')) {
        
    }
    else {
        if (prevPromo.attr('href')) {
            
        }
        else {
            $('<a class="space"></a>').insertBefore(nextPromo);
        }
        
    }
});

I don't mind if we have to do this through a completely different approach.

Edit 2: I have had somewhat of a partial success with my script. The problem occurs when there's more than 2 anchors. No matter what, I'd like there to only be not more than 2 anchors before each div. So if there's 3 <a> elements in a row, we can push the last one to come after the div instead so its always like how I want it to be.

about 4 years ago · Juan Pablo Isaza
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!