0

If I click on a specific list item then it will goes to up in the list. For example if i click on Price list it show above of the color list.

function setOnTop() {
  var listItems = document.querySelector("li");
  for (var i = 0; i < listItems.length; i++) {
    listItems[$i].addEventListener("click", function() {
      //Move on top
    });
  }
}
<ul>
  <li>Color</li>
  <li>Size</li>
  <li>Price</li>
</ul>
isherwood
  • 58,414
  • 16
  • 114
  • 157

1 Answers1

2

const ul = document.querySelector("ul");
const li = ul.querySelectorAll("li");

function setTop() {
  ul.prepend(this);
}
li.forEach((el) => {
  el.addEventListener("click", setTop);
});
<ul>
  <li>Color</li>
  <li>Size</li>
  <li>Price</li>
</ul>
isherwood
  • 58,414
  • 16
  • 114
  • 157
bluestar0505
  • 338
  • 1
  • 14
  • when you prepend the li why doesn't it add to the list of li(s) instead of moving the li from one place to another? – DCR Jan 27 '23 at 18:00