Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Style a collection of elements quickly (See related posts)

Quickly set multiple style properties to single elements or arrays/nodeLists of elements.

function setStyles(el, css) {
	var l = el.length;
	if (typeof l == 'undefined') {el = [el]; l = 1;}
	for (var i=0; i<l; i++) {
		for (var s in css) el[i].style[s] = css[s];
	}
}


Usage:

window.onload = function() {
	// single element
	setStyles(document.body, {background:'yellow'});
	// nodeList
	setStyles(document.getElementsByTagName('div'), {
		background: '#def',
		color: 'red'
	});
	// array
	var a = [document.body, document.getElementsByTagName('div')[0]];
	setStyles(a, {border: '1px black dotted'});
};

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts