开发者

add id to li a using jquery

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:

开发者_JAVA技巧<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 :)


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)


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>


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');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜