skip to Main Content

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 class="navbar-nav">
  <li class="nav-item dropdown">
    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"></a>
      <ul class="dropdown-menu">
         <li><a class="dropdown-item" href="#">Link 1</a></li>
         <li><a class="dropdown-item" href="#">Link 3</a></li>
       </ul>
  </li>
</ul>

Javascript Code –

if (role == "admin") {
  $(".dropdown-menu").append('<li>'+
  '<a class="dropdown-item" 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

2

Answers


  1. if (role == "admin") {
      $(".dropdown-menu :first").after('<li>'+
      '<a class="dropdown-item" href="#">Link 2</a>'+
       '</li>');
    }
    
    Login or Signup to reply.
  2. 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 class="dropdown-item" 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 class="navbar-nav">
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"></a>
          <ul class="dropdown-menu">
             <li><a class="dropdown-item" href="#">Link 1</a></li>
             <li><a class="dropdown-item" href="#">Link 3</a></li>
           </ul>
      </li>
    </ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search