Reputation: 7768
I have two identical <ul>
list ,I need to reverse the order of the two list using jQuery when i press a button.I have tried the bellow code and it is not working as expected.
function spin(){
spinList($('.list-view'));
}
var spinList = function($el){
var elementClone = $el.eq(0).clone();
var allLength = elementClone.find('li').length;
for(var i = 0;i<allLength;i++){
var element = elementClone.find('li').eq(allLength-i).clone();
$el.eq(0).find('li').eq(i).replaceWith(element);
$el.eq(1).find('li').eq(i).replaceWith(element);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="spin()">Change order</button>
<ul class="list-view">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>
<ul class="list-view">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>
Upvotes: 1
Views: 115
Reputation: 3816
Without jQuery, with some ES6 features:
function spin() {
var lists = document.querySelectorAll('.list-view');
Array.from(lists).forEach((list) => {
var reversed = Array.from(list.querySelectorAll('li')).reverse();
list.innerHTML = '';
var fragment = document.createDocumentFragment();
reversed.forEach((item) => {
fragment.appendChild(item);
})
list.appendChild(fragment);
})
}
<button onclick="spin()">Change order</button>
<ul class="list-view">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>
<ul class="list-view">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>
Upvotes: 0
Reputation: 115242
Use native JavaScript reverse()
method
function spin() {
spinList($('.list-view'));
}
var spinList = function($el) {
$el.each(function() { // iterate over the list
$(this).append( // appending to change the order
$('li', this) // get the li element
.get() // get them as array
.reverse() // reverse the order
)
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="spin()">Click</button>
<ul class="list-view">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>
<ul class="list-view">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
</ul>
Upvotes: 5