george george - 1 month ago 10
HTML Question

jquery change element position in dom

Hey i wanna change position of some element in DOM, for example .off-date in .teach2 but if these elements are twice or more on page it prepands two or more elements instead just one, so the result is that i got four .off-date elements on page instead just two .. Can i prevent this somehow ? Any advice welcomed..

if ($(window).width() < 767) {

$(".teach2 .off-place").prependTo($(".teach2 .off-date"));

}


<div class="teacher-box teach2">

<span class="typo off-name">Magdalene</span>
<span class="typo off-type">with partners</span>
<span class="typo off-date">wed DEC 15 </span>
<span class="typo off-time">19.30 - 20.30</span>
<span class="typo off-place">at home</span>

</div>

<div class="teacher-box teach2">

<span class="typo off-name">Magdalene</span>
<span class="typo off-type">with partners</span>
<span class="typo off-date">wed DEC 15 </span>
<span class="typo off-time">19.30 - 20.30</span>
<span class="typo off-place">at home</span>

</div>

Answer

You need to use .each() to iterate over each .off-place, so you can prepend it to the .off-date in the same DIV.

$("#but").click(function() {
  $(".teach2 .off-place").each(function() {
    $(this).prependTo($(this).siblings(".off-date"));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="but">Click to move</button>
<div class="teacher-box teach2">

  <span class="typo off-name">Magdalene</span>
  <span class="typo off-type">with partners</span>
  <span class="typo off-date">wed DEC 15 </span>
  <span class="typo off-time">19.30 - 20.30</span> 
  <span class="typo off-place">at home</span>

</div>

<div class="teacher-box teach2">

  <span class="typo off-name">Magdalene</span>
  <span class="typo off-type">with partners</span>
  <span class="typo off-date">wed DEC 15 </span>
  <span class="typo off-time">19.30 - 20.30</span>
  <span class="typo off-place">at home</span> 

</div>

Comments