almost 9 years ago
Hello readers, in this tutorial we will learn about how to get style information for an element and set element style with one or more CSS.
Whenever you need to get information about style which is inline or via javascript and also need to know directly about the element style property. we use :-
Syntax:-
If you need to know about the information of the existing style of the particular element, we use the function :-
function getStyle(elem, cssprop, cssprop2){
// IE
if (elem.currentStyle) {
return elem.currentStyle[cssprop];
// other browsers
} else if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(elem, null).getPropertyValue(cssprop2);
// fallback
} else {
return null;
}
}
window.onload=function() {
// setting and accessing style properties
var elem = document.getElementById("elem");
var color = getStyle(elem,"backgroundColor", "background-color");
alert(color); // rgb(0,255,0)
}
function getStyle(elem, cssprop, cssprop2){
// IE
if (elem.currentStyle) {
return elem.currentStyle[cssprop];
// other browsers
} else if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(elem, null).getPropertyValue(cssprop2);
// fallback
} else {
return null;
}
}
window.onload=function() {
// setting and accessing style properties
var elem = document.getElementById("elem");
var color = getStyle(elem,"backgroundColor", "background-color");
alert(color); // rgb(0,255,0)
}
Every web page element has their own property and methods. One of the properties of the element is that the style object, it represent the CSS style for that particular element. There are many ways to know the style information. First is, you can access directly to the object style, by using the dot notation which is mainly used to access the object properties and methods:
Syntax:-
With this approach, you can get and set the style setting inline or dynamically but there is a special syntax to use this.
Syntax:-
Use the Camel-Case when you have the property which is using with hyphens such are like background-color:-
Syntax:-
While if you use property with hyphen it doesn't work, because javascript interact with hyphen as a subtraction operator.
The next approach of accessing the style is the method of "getAttribute" to get the style object:-
Syntax:-
However, you would then have to resolve into its component parts the values comes out of the string. It is better you can just access directly the values on the style property.
Can you help out the community by solving one of the following Javascript problems?
Do activity (Answer, Blog) > Earn Rep Points > Improve Rank > Get more opportunities to work and get paid!
For more topics, questions and answers, please visit the Tech Q&A page.
0 Comment(s)