Florin Simion Florin Simion - 15 days ago 7
Javascript Question

Move more elements with same class in the DOM

I have the following code and I want to move the 'a' tag on top of the two parents (other-div and some-other-div)

<div class="container">
<div class="some-other-div">
<div class="other-div">
<a class="link" href="#">move me<a>
</div>
</div>
<div class="some-other-div">
<div class="other-div">
<a class="link" href="#">move me<a>
</div>
</div>
</div>


To look like this

<div class="container">
<a class="link" href="#">move me<a>
<div class="some-other-div">
<div class="other-div">

</div>
</div>
<a class="link" href="#">move me<a>
<div class="some-other-div">
<div class="other-div">

</div>
</div>
</div>


this is a pen I've created:

http://codepen.io/florinsimion/pen/qqRWOo

any ideas?

Answer

Use before() method with a callback function which iterates over the elements and inside the callback return the a tag to be moved.

$('.some-other-div').before(function() {
  return $(this).find('.link');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="some-other-div">
    <div class="other-div">
      <a class="link" href="#">move me</a>
    </div>
  </div>
  <div class="some-other-div">
    <div class="other-div">
      <a class="link" href="#">move me</a>
    </div>
  </div>
</div>

Comments