0

This is my html code. I am trying to make this link different color but using jquery.

nav ul li:nth-child(1) a { color: orange; }
nav ul li:nth-child(2) a { color: red; }
nav ul li:nth-child(3) a { color: green; }
nav ul li:nth-child(4) a { color: brown; }
nav ul li:nth-child(5) a { color: yellow; }
nav ul li:nth-child(6) a { color: purple; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<nav>
  <ul>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</nav>

also active link will be black(#000) color.and active link background will be the link color.

2 Answers 2

4

You can store your colors into an array, then using selector get the lis and iterate over them. In each iteration use jQuery#css function to apply the colors using the index of the li in the list and index of the color in the colors.

But it is better to use css to apply styles to the items. Only dynamic changed styles must be applied using jQuery. How many works will be set on the css instead of jQuery, faster it will work.

const colors = [ 'orange', 'red', 'green', 'brown', 'yellow', 'purple'];

$('nav ul li a').each(function(index, item) {
   $(item).css('color', colors[index]);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav>
  <ul>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
</ul>
</nav>

Sign up to request clarification or add additional context in comments.

2 Comments

you may need to add a in your selector
thank you @ Temani it works good.but when a link will be active..then it's background will be this link-color.and this link color will be black (#000). is that possible to do that....? i am working with bootstrap tabs/pills Toggleable / Dynamic Tabs
0

Check this.Tested!!!

 <script>
   $(document).ready(function(){

    $('ul li a').each(function(index,item) {
       //color = "#"+Math.floor(Math.random()*16777215).toString(16);
       //select = "ul > li:nth-child("+i+") > a";
       color  = getRandomColor();
       $(item).css('color',color);
    });

   });

   function getRandomColor() {
      var letters = '0123456789ABCDEF';
      var color = '#';
      for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
     }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.