How To Reverse All LI From A UL List Using Javascript
In This Javascript Tutorial we will See How To Reverse All <LI> Elements From A <UL> List Using Array And For Loop In JS And Netbeans Editor .
Project Source Code:
<!DOCTYPE html>
<html>
<head>
<title>Javascript: reverse All LI</title>
<meta charset="windows-1252">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<ul id="list">
<li>0</li>
<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>
</ul>
<script>
var items = document.querySelectorAll("#list li"),
tab = [];
// populate array with li values
for(var i = 0; i < items.length; i++){
tab.push(items[i].innerHTML);
}
// clear UL
document.getElementById("list").innerHTML = "";
var list = document.getElementById("list");
tab.reverse();
for(var i = 0; i < tab.length; i++){
var textNode = document.createTextNode(tab[i]),
liNode = document.createElement("LI");
liNode.appendChild(textNode);
list.appendChild(liNode);
}
</script>
</body>
</html>
OUTPUT: