How to Pass a Variable Number of Parameters to a Javascript Function

Ever came across a situation when you want to pass multiple parameters to a Javascript function but you do not know how many of those there are? For example, maybe you have an HTML page with a table that is populated dynamically and you want to perform something on some rows but you do not know in advance their IDs. Do not worry, you can easily do it with arguments variable, which is local to your function and is an array of all parameters passed to the function. As you may know from the previous post, you are not required to pass any parameters to a function, even if you declare it to have some, and not passing them will not result in an error.

Now, onto the code, based on the table example above. I would like to pass any number of <tr> element ID’s to the function so that the background of each of them is red:

function updateRowBackgrounds()
{
	for (var i = 0; i < arguments.length; i++)
	{
		var row = document.getElementById(arguments[i]);
		if (typeof row == 'undefined') { continue; }
		row.style.background = '#ff0000';
	}
}

updateRowBackgrounds('tr1', 'tr5', 'tr3');
updateRowBackgrounds('tr10');

In this example, we iterate through every parameter that is passed to the function and get the corresponding HTML element. We then check whether such element exists and if it does, we change the background.

This entry was posted in Javascript and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *