Over a million developers have joined DZone.

Cross-browser Way To Retrieve Styles For Elements Via The DOM

·
document.getElementById('whatever').style only gives local styles, but if you want those specified in external CSS definitions, you have to arse about (why, oh, why?) and do it like this:


function newGetStyle(nodeName, sStyle) {
	var x = document.getElementById(nodeName);
	var y;
	if (x.currentStyle) {
		y = x.currentStyle[sStyle];
	} else {
		try {
		y = document.defaultView.getComputedStyle(x,null).getPropertyValue(sStyle);
	  } catch(e) { }
	}
	return y;
}
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}