-2

As the title says I want to have string classes rather than numeric, this is the script I currently have!

$('ul#nav li').each(function (index, element) {
    $(element).addClass('number_' + (index+1).toString());
});

And this is what I get, it works fine and nothing wrong with it;

<ul id="nav">
    <li class="number_1"></li>
    <li class="number_2"></li>
    <li class="number_3"></li>
    <li class="number_4"></li>
    <li class="number_5"></li>
</ul>

But I want it to return the classes as in string and NOT numeric! So something like this;

<ul id="nav">
    <li class="first"></li>
    <li class="second"></li>
    <li class="third"></li>
    <li class="fourth"></li>
    <li class="fifth"></li>
</ul>

PLEASE NOTE: These classes are generated/added dynamically, therefore the string classes should be added dynamically, so may have 100 list items!

Thank you for your time, appreciate any help :)

ZAD
  • 569
  • 2
  • 7
  • 23
  • 1
    nice thought. but right now there are no ready functions in jquery that u can use to achieve this. – Bhadra Nov 21 '13 at 08:53
  • 1
    Yes, it's achievable. Only if you have a dictionary with mappings like `[ '1': 'first', '2': 'second', '3' => 'third', ... ]` – Aniket Nov 21 '13 at 09:07
  • That's what I was thinking to do, so maybe have an function that does this and then use that over and over again :) – ZAD Nov 21 '13 at 09:16
  • There is no easy solution. You should define every translation for each number: [Example](http://jsfiddle.net/H3rr3/) – nkmol Nov 21 '13 at 09:22
  • True! Maybe I need to come up with some algorithm that does this... very complicated though, I know it's crazy way but I have no choice :( the element I'm trying to use it for has many many many classes and to be honest I was confused when other devs in my team came with such idea :( – ZAD Nov 21 '13 at 09:36

1 Answers1

2

What you want makes no real sense, but you can realize it with an array :

<script type="text/javascript">
   var listClasses = new Array("first", "second", "third", "fourth",.....);
</script>

And then use your code a little bit modified:

$('ul#nav li').each(function (index, element) {
    $(element).addClass(listClasses[index]);
});
mahega
  • 3,231
  • 4
  • 20
  • 32
  • Thanks, yes I know it doesn't makes sense but due to my limitation I can't use numeric classes! I've already had it as an array but that means I have to add the classes manually :( Cheers – ZAD Nov 21 '13 at 09:03
  • Have you looked at http://stackoverflow.com/questions/15809950/javascript-ordinal-suffix-for-numbers-with-specific-css-class? it looks like someone else was trying to do the same thing. Maybe one of those answers can help you figure out how to not use an array, but generate the words algorithmically. – mr rogers Nov 21 '13 at 09:10
  • Yes mate already looked at that but still uses numbers at the beginning which isn't allowed in CSS :) – ZAD Nov 21 '13 at 09:14