How to Exchange the position with it sibling with jquery?

Viewed 28

How can I use jquery to make each content of the P exchange the position with it own h2 sibling?

<div>
    <div>
        <h2 class="title">Hello 1</h2>
        <p class="content-info">good day</p>
    </div>

    <div>
        <h2 class="title">Hello 2</h2>
        <p class="content-info">good day</p>
    </div>

        <div>
        <h2 class="title">Hello 3</h2>
        <p class="content-info">good day</p>
    </div>
</div>

Ideally the outcome I want is like this...

Good Day
Hello 1

Good Day
Hello 2

Good Day
Hello 3

I try to use

$(".content-info").insertAfter(".title");

But the outcome would become like this...

Good Day
Good Day
Good Day
Hello 1

Good Day
Good Day
Good Day
Hello 2

Good Day
Good Day
Good Day
Hello 3

Is there any jquery solution for just making the element exchange with its own sibling only?

Thank

3 Answers

You could try with:

$(".content-info").each(function() {
  $(this).insertBefore($(this).prev(".title"))
});

Problem with your attempt is that it will insert all 3 content-info before each .title

Demo

$(".content-info").each(function() {
  $(this).insertBefore($(this).prev(".title"))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
    <div>
        <h2 class="title">Hello 1</h2>
        <p class="content-info">good day</p>
    </div>

    <div>
        <h2 class="title">Hello 2</h2>
        <p class="content-info">good day</p>
    </div>

      <div>
        <h2 class="title">Hello 3</h2>
        <p class="content-info">good day</p>
    </div>
</div>

Without accessing the tagName or class

$("div div").each(function() {
  $(this).children().eq(0).appendTo(this)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>
  <div>
    <h2 class="title">Hello 1</h2>
    <p class="content-info">good day</p>
  </div>

  <div>
    <h2 class="title">Hello 2</h2>
    <p class="content-info">good day</p>
  </div>

  <div>
    <h2 class="title">Hello 3</h2>
    <p class="content-info">good day</p>
  </div>
</div>

Accessing the title:

$("div div .title").each(function() {
  const $parent = $(this).closest("div")
  $(this).appendTo($parent)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div>
  <div>
    <h2 class="title">Hello 1</h2>
    <p class="content-info">good day</p>
  </div>

  <div>
    <h2 class="title">Hello 2</h2>
    <p class="content-info">good day</p>
  </div>

  <div>
    <h2 class="title">Hello 3</h2>
    <p class="content-info">good day</p>
  </div>
</div>

$(".content-info").each(function(i, a){
  $(a).prev().prepend(a)
})
Related