style.display in Javascript

	// Quick example: Grab the first <div> on the page and make it disappear.
	document.getElementsByTagName('div')[0].style.display = 'none';

Most front-end web developers are familiar in some fashion with both CSS and Javascript. The style property is how Javascript gets and sets the CSS information for an element.

Every CSS style can be set using Javascript, but it only applies it to the element. It does not change the external CSS file, or change any style declarations in the page.

So if you have an element in Javascript that you want to set the CSS display property, you can simply overwrite it, or other style properties:

	// Get an element with the id attribute of testing, like:
	// <div id="testing">Text here.</div>
	var myElement = document.getElementById('testing');

	// Now hide that element, by setting display to none
	myElement.style.display = 'none';

	// Set the display to block, overwriting the none.
	myElement.style.display = 'block';

	// And then turn it green
	myElement.style.background = 'green';

In the case of style properties that have two words separated by a dash, like font-size, the style property is written in camelCase. So to set the font-size property of your element you use style.fontSize:

	// Set the size of the type really big.
	myElement.style.fontSize = '48px';

Comments