Reading and changing inline styles

Download dom eBook

Example

Inline style

You can manipulate the inline CSS style of an HTML element by simply reading or editing its style property.

Assume the following element:

<div id="element_id" style="color:blue;width:200px;">abc</div>

With this JavaScript applied:

var element = document.getElementById('element_id');

// read the color
console.log(element.style.color); // blue

//Set the color to red
element.style.color = 'red';

//To remove a property, set it to null
element.style.width = null;
element.style.height = null;

However, if width: 200px; were set in an external CSS stylesheet, element.style.width = null would have no effect. In this case, to reset the style, you would have to set it to initial: element.style.width = 'initial'.

Stats

Contributors: 4
2016-08-22
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook