tags:

views:

246

answers:

3

Hi all,

I'm looking for something that will allow me to add an id tag to the 9th li a tag in my list.. I'm not even sure if it's possible?

Here's the code:

<ul id="p7menubar">
  <li><a href="#" class="trigger">Home</a></li>
  <li><a href="#" class="trigger">About Us</a></li>
  <li><a href="#" class="trigger">Collections</a></li>
  <li><a href="#" class="trigger">Stockists</a></li>
  <li><a href="#" class="trigger">News / Press</a></li>
  <li><a href="#" class="trigger">How to Order</a></li>
  <li><a href="#" class="trigger">Terms & Conditions</a></li>
  <li><a href="#" class="trigger">Contact Us</a></li>
  <li><a href="#" class="trigger" XX ID TAG TO GO HERE XX >Online Store</a>
    <ul id="menuitem_9_0">
      <li><a href="#" >Baby Clothing</a></li>
      <li><a href="#" >Boys Clothing</a></li>
      <li><a href="#" >Girls Clothing</a></li>
    </ul>
  </li>
</ul>

If anyone could help me out, that'd be great :)

+6  A: 

In jQuery you should be able to do the whole thing in a single selector:

$("#p7menubar > li:nth-child(9) > .trigger").attr("id","MyNewID");

"Match a tag with a class of trigger inside the ninth LI tag within p7Menubar".

Update: It appears I was wrong, nth-child is 1-indexed. Also updated to be more explicit (thanks Joel Potter)

Matt Baker
thanks! works well :)
SoulieBaby
You should use direct child "`>`" just in case there are nested lists inside any of the earlier `li`s.
Joel Potter
A: 

I believe the fastest method would be the following:

$('#p7menubar').find('li:eq(8)').attr('id', 'yourID');

Someone please correct me if I'm wrong but I believe this is optimized by first utilizing getElementById due to a single ID selector prior to find().

UPDATE

$('#p7menubar > li:eq(8)').attr('id', 'yourID');
cballou
This method will not work if there are child `li` within the level 1 `li` before the 9th one.
o.k.w
good catch. should've paid attention to nested lists. +1
cballou
A: 

Myles' solution (deleted) is ALMOST a bingo but he missed out the "#" selector prefix for id.

I've tried his code and it works!

<a onclick="$('#p7menubar').children()[8].id = 'QWERTY';">id it!!</a>
o.k.w