Home > front end >  How to Exchange the position with it sibling with jquery?
How to Exchange the position with it sibling with jquery?

Time:09-23

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

<div>
    <div>
        <h2 >Hello 1</h2>
        <p >good day</p>
    </div>

    <div>
        <h2 >Hello 2</h2>
        <p >good day</p>
    </div>

        <div>
        <h2 >Hello 3</h2>
        <p >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

CodePudding user response:

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 >Hello 1</h2>
        <p >good day</p>
    </div>

    <div>
        <h2 >Hello 2</h2>
        <p >good day</p>
    </div>

      <div>
        <h2 >Hello 3</h2>
        <p >good day</p>
    </div>
</div>

CodePudding user response:

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 >Hello 1</h2>
    <p >good day</p>
  </div>

  <div>
    <h2 >Hello 2</h2>
    <p >good day</p>
  </div>

  <div>
    <h2 >Hello 3</h2>
    <p >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 >Hello 1</h2>
    <p >good day</p>
  </div>

  <div>
    <h2 >Hello 2</h2>
    <p >good day</p>
  </div>

  <div>
    <h2 >Hello 3</h2>
    <p >good day</p>
  </div>
</div>

CodePudding user response:

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