Home > database >  How can i move HTML elements outside their containers using Jquery?
How can i move HTML elements outside their containers using Jquery?

Time:06-03

I need to move the p tag in each container outside it's container, so i need to move "some text 1" outside its container and the same to the next paragraph , but what i'm getting is the both of them are moving out side the containers

$(document).ready(function() {
  
    $('.select-p-container p').each(function () {
    $(this).insertBefore('.select-p-container');
  })
   
 
});
.select-p-container{
  border:1px solid red;
  max-width:450px;
  margin-bottom: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <div >
      <p>Some text 1</p>
      <select name="" id="">
        <option value="1">1</option>
        <option value="1">2</option>
        <option value="1">3</option>
      </select>
    </div>
      <div >
      <p>Some text 2</p>
      <select name="" id="">
        <option value="1">1</option>
        <option value="1">2</option>
        <option value="1">3</option>
      </select>
    </div>
  </div>
</div>

CodePudding user response:

You need to properly limit the scope of your element selection.

$(this).insertBefore('.select-p-container')

.select-p-container selects all elements with that class, across the whole document.

You need only the element, that is the actual parent of the current paragraph:

$(this).insertBefore($(this).parent());
  • Related