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

About this user

Steve Clay http://mrclay.org/

« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS 

Style a collection of elements quickly

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'});
};

Empty a DOM node

while (node.hasChildNodes()) {node.removeChild(node.firstChild);}

Faster looping over DOMCollections

var i=0, el;
while (el = document.getElementsByTagName('div').item(i++)) {
    // use el here
}


Calling document.getElementsByTagName('div').item() directly saves the browser from having to return a whole DOMCollection. Using the while loop prevents the browser from ever having to calculate a DOMCollection's length, and gives us a syntactically nicer reference to the current node.

Source: David "liorean" Andersson. Here's an e-mail excerpt:

> DOM implementations are optimised for single element access, and DOMCollections [like document.getElementsByTagName()] are particularly badly optimised since they are dynamic, which means they need to be either polled at regular intervals, event controlled or recollected at each access. So, instead of caching the DOMCollection, you can make the script never have to create a DOMCollection at all. A perfomance win that will be considerable, and that can actually be felt if you're doing DHTML. ... [calling item() directly, the browser] never has to create a dynamic collection, it just searches for the element with the given order, and discards the created list. Browsers do optimise for accessing collection members this way.
« Newer Snippets
Older Snippets »
Showing 1-3 of 3 total  RSS