Querying a Style Attribute

style
Consider the below html. Let us see how to query the style attribute using javascript.

snippet
<ul class="blue">
<li><a id="adidas" href="http://www.adidas.com">adidas</a></li>
<li><a id="asics" href="http://www.asics.com">ASICS</a></li>
<li><a id="brooks" href="http://www.brooksrunning.com">Brooks</a></li>
<li><a id="newBalance" href="http://www.newbalance.com">New Balance</a></li>
<li><a id="nike" href="http://www.nike.com">Nike</a></li>
<li><a id="saucony" href="http://www.saucony.com">Saucony</a></li>
</ul>

var myStyle = document.getElementById("nike").style;
myStyle.backgroundPosition;
// ""
myStyle.backgroundImage;
// ""
myStyle.left;
// ""
myStyle.top;
// ""

JavaScript returns "" as initialy there are no styles set initially in the DOM.

Writing some inline styles
var myStyle = document.getElementById("nike").style;
myStyle.backgroundPosition = "-99px -108px";
myStyle.backgroundImage = "url(images/fuchsia.gif)";
myStyle.left = "200px";
myStyle.top = "30px";

Now in the console you can see the values.

var myStyle = document.getElementById("nike").style;
myStyle.backgroundPosition;
// "-99px -108px"
myStyle.left;
// "200px"

Writing CSS properties by way of ElementCSSInlineStyle.style was equivalent to doing so by way of the following markup.
<a style="background-position:-99px -108px;backgroundimage:
url(images/fuchsia.gif);left:200px;top:30px" id="nike"
href="http://www.nike.com">Nike</a>

cssText
cssText contains the CSS text of the style attribute. Writing cssText provides a way to change several CSS properties in one go.

In the above example we will add five CSS2Properties members.

var myStyle = document.getElementById("brooks").style;
myStyle.cssText = "background-image:url(images/fuchsia.gif);left:210px;top:0;paddingleft: 99px;height:55px";

Note cssText wipes away any previous inline style which means it totally overwrite declarations. The below assignment replaces previous styles and now will have only one CSS properties.

myStyle.cssText = "background-image:url(images/fuchsia.gif)";

So, our declarations for left, top, padding-left, and height disappeared.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 # # # # #