I am trying to randomise the order of some children elements with a specific class inside a div that already contains other children elements.
I am using this, but I want to keep the order of the elements without this specific class rather than shuffle them all.
$(function () {
var parent = $(".slider-thumbs .swiper-wrapper");
var divs = parent.children();
while (divs.length) {
parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]);
}
});
Is there a way to shuffle children elements with an specific class without affecting the ones without this class?
Thanks
2
Answers
Let’s brute force our way. Shuffle, check, repeat. Then push one by one to the original parent by the order of shuffling.
I assumed you want children that without the specific class
shuffle
will remain at the same position.First give the
shuffle
class to the element that you want to included in the shuffle.Get the children which should included in shuffle.
Convert the
children
to array, perform shuffle.Then loop through the original children, replace each child with rearranged child.
Demo: