user1525612
user1525612

Reputation: 2014

addClass - one function instead of 3 functions (shorten code)

Apologies I didnt really know how to title this post.

I have the following 3 functions in YUI. What I do is look for a div with classname .box2, .box3, or .box4, and then add another class to all those divs ie the .box2 div gets another div .2

The code below works but I'm too much of a noob to get it all combined into one function for all values of the var number instead of writing it out 3 times like this.

var number = 2;
var nodes = Y.all(".box"+ number);

nodes.each(function(node){  

    node.addClass(number);

});



var number = 3;
var nodes = Y.all(".box"+ number);

nodes.each(function(node){  

    node.addClass(number);

});



var number = 4;
var nodes = Y.all(".box"+ number);

nodes.each(function(node){  

    node.addClass(number);

}); 

Thanks a million!

Upvotes: 0

Views: 88

Answers (2)

danbroooks
danbroooks

Reputation: 2800

What about this?

var numbers = [2, 3, 4];

for(var i = 0; i < numbers.length; i++)
{
  var boxnum = numbers[i];
  Y.all(".box"+boxnum ).addClass(boxnum);  
}

http://jsfiddle.net/854Th/

Upvotes: 1

mohkhan
mohkhan

Reputation: 12325

You don't have to do each. Just use addClass function on Y.all(...). Like this...

var arr = [2, 3, 4];
var query = ".box" + arr.join(", .box");
Y.all(query).addClass(levelnumber);

Upvotes: 2

Related Questions