-1

Is there a way to rearrange the order of some HTML elements using JavaScript or jQuery?

From this:

<div class="link-wrap">
 <a href="#">001</a>
 <a href="#">002</a>
 <a href="#" class="move-this">003</a>
 <a href="#" class="move-this">004</a>
 <a href="#" class="move-this">005</a>
</div>

To looks like this:

<div class="link-wrap">
 <a href="#" class="move-this">003</a>
 <a href="#" class="move-this">004</a>
 <a href="#" class="move-this">005</a>
 <a href="#">001</a>
 <a href="#">002</a>
</div>

That means whatever <a> with class move-this will be moved before others following their original order.

The challenge is that, there is no way to change the existing HTML code due to some limitations; not even to add classes or attributes to it. So, no idea how to do so after some research and testing yet.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Anthony
  • 123
  • 7
  • 1
    What have you tried so far to solve this on your own? -> [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Sep 26 '22 at 06:56
  • 1
    You can do this using CSS, if you make `.link-wrap` a `flexbox` container, then you can use `order` on the links. – CBroe Sep 26 '22 at 07:01
  • @Andreas sometimes you spend a lot of time trying, searching, and researching, you are just not able to find a hint or the answer to it... And your suggested "duplicated question" is not the same thing and does not provide a solution. – Anthony Sep 26 '22 at 07:04
  • That's not my dupe but I can live with it. I've voted to close this question as it needs more details ;) – Andreas Sep 26 '22 at 07:06
  • @CBroe that's a great hint, I don't know it exists before, thanks!! yes, I can make it flex by custom CSS. Order property: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Ordering_Flex_Items#the_order_property – Anthony Sep 26 '22 at 07:24

1 Answers1

1

You can use jQuery prepend to move the desired elements to the beginning of the .link-wrap div:

$('.link-wrap').prepend($('.link-wrap .move-this'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="link-wrap">
 <a href="#">001</a>
 <a href="#">002</a>
 <a href="#" class="move-this">003</a>
 <a href="#" class="move-this">004</a>
 <a href="#" class="move-this">005</a>
</div>
Nick
  • 138,499
  • 22
  • 57
  • 95