Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

·
Free Resource
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:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}