Florin Simion
Florin Simion

Reputation: 458

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?

Upvotes: 2

Views: 99

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

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>

Upvotes: 2

Related Questions