Home > Software engineering >  How to show dropdown links in a particular order?
How to show dropdown links in a particular order?

Time:11-14

I want to show the drop-down links in a particular order. Right now the order is -

  • Link 1
  • Link 3
  • Link 2

HTML Code -

<ul >
  <li >
    <a  href="#" role="button" data-bs-toggle="dropdown"></a>
      <ul >
         <li><a  href="#">Link 1</a></li>
         <li><a  href="#">Link 3</a></li>
       </ul>
  </li>
</ul>

Javascript Code -

if (role == "admin") {
  $(".dropdown-menu").append('<li>' 
  '<a  href="#">Link 2</a>' 
   '</li>');
}

Can anyone tell me how can I show the links in the following order?

  • Link 1
  • Link 2
  • Link 3

CodePudding user response:

Try getting the textContent of the a tag after append and sort it out using textContents.sort() and then iterate the sorted textContents and update the anchor tag values back.

const role = 'admin';

if (role == "admin") {
  $(".dropdown-menu").append('<li>' 
  '<a  href="#">Link 2</a>' 
   '</li>');
}

  const anchors = $(".dropdown-menu").children('li').children('a');

  // extract the text
  const textContents = anchors.get().map((item) => item.textContent);

  // sort the text
  textContents.sort();

  // show reordered texts back into the original elements
  textContents.forEach((value, index) => {
    anchors[index].textContent = value;
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul >
  <li >
    <a  href="#" role="button" data-bs-toggle="dropdown"></a>
      <ul >
         <li><a  href="#">Link 1</a></li>
         <li><a  href="#">Link 3</a></li>
       </ul>
  </li>
</ul>

CodePudding user response:

if (role == "admin") {
  $(".dropdown-menu :first").after('<li>' 
  '<a  href="#">Link 2</a>' 
   '</li>');
}
  • Related