PrependTo item only ONCE in Jquery

时间:2017-07-12 08:01:32

标签: jquery

I have the following DOM-tree relationship

<div class="div-class"></div>
<table class="table-class"></table>

<div class="div-class"></div>
<table class="table-class"></table>

What I would like to do is move the .table-class inside the .div-class, but when I run jQuery with prependTo('.div-class') I get the following output:

<div class="div-class">
  <table class="table-class"></table> <!-- they get added TWICE -->
  <table class="table-class"></table> <!-- they get added TWICE -->
</div>

<div class="div-class">
  <table class="table-class"></table> <!-- they get added TWICE -->
  <table class="table-class"></table> <!-- they get added TWICE -->
</div>

I just need to move the first/immediate occurrence of .table-class inside that div.class. Any pointers?

3 个答案:

答案 0 :(得分:0)

The issue is because you're prepending all the .div-class elements to all the .table-class elements at once.

To solve this you can use prepend() on the .div-class elements, passing the method a function which returns the element to prepend to. Try this:

$('.div-class').prepend(function() {
  return $(this).next('table');
});
div { 
  padding: 10px;
  margin: 0 0 10px;
  border: 1px solid #C00; 
}
table { 
  height: 20px;
  border: 1px solid #0C0; 
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div-class"></div>
<table class="table-class"></table>

<div class="div-class"></div>
<table class="table-class"></table>

答案 1 :(得分:0)

As of now you are prepending the table to all .div-class element. You can iterate are relatively prepend element.

$('.table-class').each(function() {
  $(this).prependTo($(this).prev('.div-class'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div-class">First Div</div>
<table class="table-class">
  <tr>
    <td>1</td>
  </tr>
</table>
<div class="div-class">Second Div</div>
<table class="table-class">
  <tr>
    <td>2</td>
  </tr>
</table>

答案 2 :(得分:0)

Try with next()

$('.div-class').each(function(){
  $(this).prepend(function() {
    return $(this).next('.table-class')
  })
})
console.log($('body')[0].outerHTML)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div-class">
</div>

<table class="table-class" id="one">
</table>


<div class="div-class">
</div>

<table class="table-class" id="two">
</table>

相关问题