dzimi
dzimi

Reputation: 829

Append each element to closest anchor

I have this html:

<div class="col">
    <div class="prevnextbg">prevnextbg</div>
    <a href="#"></a>
</div>

<div class="col">
    <div class="prevnextbg">prevnextbg</div>
    <a href="#"></a>
</div>

I want to take each .prevnextbg and add it inside the <a> inside it's .col div.

I tried like so but that just adds all the .prevnextbg divs to the first <a>:

$('div.prevnextbg').appendTo('.col a');

Upvotes: 1

Views: 54

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

You can't do it in one call, you need a loop:

$(".prevnextbg").each(function() {
    $(this).siblings("a").append(this);
});

Live Example:

$(".prevnextbg").each(function() {
  $(this).siblings("a").append(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col">
    <div class="prevnextbg">prevnextbg</div>
    <a href="#"></a>
</div>

<div class="col">
    <div class="prevnextbg">prevnextbg</div>
    <a href="#"></a>
</div>

If the a elements may not be siblings, you might do

$(".prevnextbg").each(function() {
    $(this).parent().find("a").append(this);
});

instead.


That said, it would be much better to modify the markup to start with, rather than rearranging it after the fact.

Upvotes: 2

Related Questions