Adding attributes to elements using jQuery
As promised in yesterday’s post, today I am going to show you how to add id’s to a bunch of elements. Everyone has created navigation menus using unordered lists. Very common thing right? Well, sometimes you have to actually style every list item or ‘a’ tag differently. I’m going to show you to use jQuery to add a different id to each list item in a typical navigation. So first, I’ll give you the simple html:
<ul id="navigation"> <li><a href="index.php">Home</li> <li><a href="about.php">About</li> <li><a href="portfolio.php">Portfolio</li> <li><a href="contact.php">Contact</li> <li><a href="/blog">Blog</li> </ul>
Pretty straight forward list. Here is the jQuery:
$(document).ready(function() { $('#navigation li').each(function(index) { $(this).attr({ 'id': 'nav-' + index }); }); });
That finds every li within the ul with an id of ‘navigation’, and for each of them give it an id of ‘nav-’ and whatever number it is in the index. So the first li in the list would have an id of ‘nav-0′. Since the index starts at 0. Now that you know how to do that, you can add any attribute you want to anything, be it a title, an href, its all up to you. Hop to it.
jQuery junkBox
$.merge(firstArray, secondArray);
This merges the contents of the second array into the first. So the below code would print out: 0, 1, 2, 3, 4
var firstArray = [0, 1, 2]; var secondArray = [3, 4]; var finalArray = $.merge(firstArray, secondArray); $.print(finalArray);
Tags: jQuery






I used the .attr today in one of my first “real” jQuery projects.
http://mcculloughdesigns.com/samples/eaglesteel/buildings.php
Was really nifty when replacing an image.
But I noticed something weird happening in the process of the project:
Have you ever had it when jQuery is inconsistent with CSS positioning?
I assume you mean top/left positioning? Not that I am aware of. What was it doing exactly?
Well I was doing the sprite slideshow that you did, and occasionally it would be off by a pixel in the console. I was doing like left: -=500 and occasionally a -499 would show up, for example.
That is odd as heck. Did it look off? Or was it just showing the -499 in the console but still look right? Did you correct it, and do you have a link I can see it?
It’s actually the link up there. I had each arrow for the thumbnail viewer set to hide whenever the thumbnail viewer ‘left’ property was at a certain value (that way it wouldn’t just keep on going). Since it was 1px off, it wouldn’t disable it, and I had to make an ugly fix to the code logic.
What was strange was that if I clicked the right arrow, the left would be set to -179, but clicking the left arrow to return it back to original position, left would be 0. This means there is a fault of 1 somewhere.
I’ll replace the condensed script with the actual one so you can view it in source.