简体   繁体   中英

jQuery get previous position of element

I looking for a way to find out previous place of element before append , I have 50 element that should append to different elements but in a certain statement, the question is how can I find previous location of each element?

 $('#statment').change(function() { var val = $(this).val(); if (val === "0") { $('#text1').appendTo('#target'); $('#text2').appendTo('#target'); } else if (val === "1") { $('#text1').appendTo('#old'); $('#text2').appendTo('#old'); // Detect previous place?? } }); 
 #target { padding: 10px; border: 1px dashed red; width: 200px; margin-top: 10px; } #old { padding: 10px; border: 1px dashed blue; width: 200px; margin-top: 10px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="statment" type="number" value="1" min="0" max="1" /> <div id="target"></div> <div id="old"> <a id="text1">Text 1</a> <a id="text2">Text 1</a> </div> 

This is just a sample of my real code, the real code is too large for share.

I need in else instead of bring back each element to old parent, detect previous position of each element. Is it possible?

$('#text1').appendTo('#target'); so how can I find the origin position of this element?

One way would be to leave a "trace" in the original location when you move the element away from it. Like an empty <span> that has an attribute referring to the element that was there.

Here is how that could work:

 $('#statment').change(function() { var val = $(this).val(); if (val === "0") { $('#text1,#text2').each(function () { // Only move the element when it is not yet within the target area if (!$(this).closest("#target").length) { $(this).wrap($('<span>').attr("data-ref", this.id)).appendTo('#target'); } }); } else if (val === "1") { $('span[data-ref]').each(function () { $(this).replaceWith($('#' + $(this).data("ref"))); }); } }); 
 #target { padding: 10px; border: 1px dashed red; width: 200px; margin-top: 10px; } .old { padding: 10px; border: 1px dashed blue; width: 200px; margin-top: 10px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="statment" type="number" value="1" min="0" max="1" /> <div id="target"></div> <div class="old"> <a id="text1">Text 1</a> </div> <div class="old"> <a id="text2">Text 2</a> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM