'How to Use PrependTo Dynamically on each Element

I have a requirement where an element with a particular class has to be prepended to its sibling with another class. Although I am able to achieve this for the first instance, it doesn't work for all the elements in the div. I have tried the below code

Click Here

This Works:
$("#MyDiv .spanToBeShifted:first").prependTo($("#MyDiv .MyButton:first"));


This Doesnt:
$("#MyDiv .spanToBeShifted").prependTo($(this).closest('.MyButton'))


Solution 1:[1]

Below is the solution which worked for me

Solution

$('.spanToBeShifted').each(function () {
    var d = $(this).siblings('.MyButton');
    
    $(this).prependTo(d)
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 shadab momin