forkhyun (27) [Avatar] Offline
#1
Hi All,

I am going through Chapter 3, on page 66.

As you know, there are three ways of using this method. One is that you input the class name in the parameter. Second is that you input more than one class name by spacing between them.

Third one is looking like: "addClass( function(index, currentClass) )."

I couldn't quite understand this third one.

I looked up on the internet to apprehend this. Somehow it's not giving me some satisfying info.

Can you show me a good example for this?

Thanks in advance and look forward to hearing from you soon.
mraj (104) [Avatar] Offline
#2
Re: addClass()
Hi forkhyun,

I guess you didn't like the example here http://api.jquery.com/addClass/ ?

Suppose you have a ul with 3 li's, and this jQuery code:
$("ul li").addClass(function(index, currentClass) {
return "item-" + index;
});

The first li would get class "item-0" added to it, the 2nd li "item-1", and the 3rd li "item-2".

-- Mark
bear.bibeault (675) [Avatar] Offline
#3
Re: addClass()
Right, you'd use this format when you want to treat each element individually.
forkhyun (27) [Avatar] Offline
#4
Re: addClass()
Thanks for your example. I just wanted to find an example that uses both 'index' and 'currentClass' .

One on jQuery website showed me only currentClass part...

Do you perhaps show me any example that uses both parameters?

Thanks in advance.
bear.bibeault (675) [Avatar] Offline
#5
Re: addClass()
Actually, I think Raj did. index is just the ordinal within the "array" and it can be used for anything, including a suffix.
forkhyun (27) [Avatar] Offline
#6
Re: addClass()
Ok, you mean "item-0" , "item-1", "item-2" ... are the currentClasses?
bear.bibeault (675) [Avatar] Offline
#7
Re: addClass()
He's using the index to get the suffix numbers.
mraj (104) [Avatar] Offline
#8
Re: addClass()
Hi forkhyun,
An example that uses both 'index' and 'currentClass'...

Consider the same ul with 3 li's.
Assume the HTML document for the first li looks like this:
<li class="skip_me">, and the other two li's don't have any classes.

With this jQuery code:
$("ul li").addClass(function(index, currentClass) {
if(currentClass === "skip_me") {
return; // don't add any class to li
} else {
return "item-" + index; // add class "item-x" to li
}
});

The first li would not get any additional class added. The 2nd li would get class "item-1" added, and the 3rd li would get "item-2" added.

-- Mark
forkhyun (27) [Avatar] Offline
#9
Re: addClass()
Wow! That's very helpful. It is brilliant! Thank you