So if there is a css file linked to a webpage like:
<link href="style.css" rel="stylesheet" type="text/css">
and i want to read a certain property, e.g a div has className='layout' and i want to read the details of this property using JavaScript, how can i do that?
I have searched a lot but almost have no luck, please suggest.
Get a CSS Property Value You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css("propertyName");
The CSS of an element can be obtained using the getComputedStyle element function in JavaScript. It returns a JavaScript object containing CSS properties and their values. This object is indexed and iterable over the property names. The getPropertyValue(property) is used to get the value of a property.
First, hover over the element you want to copy. Then, right-click on it and choose the option “Inspect”. On the left side is the HTML DOM tree, and on the right side, the CSS styles of the selected element.
You can only access style properties in Javascript that have been set via Javascript (or the style attr). To access the elements current style you should fetch the computed style of the element. var el = document. getElementById('hello'); var comp = el.
You have got two options:
document.styleSheets
object (not recommended, unless you want to get all specific style properties defined by a certain selector).getComputedStyle
or currentStyle
(IE) method to get the property value.In your example, attempt to get a certain property (let's say: color
) of a div with class="layout"
:
function getStyleProp(elem, prop){
if(window.getComputedStyle)
return window.getComputedStyle(elem, null).getPropertyValue(prop);
else if(elem.currentStyle) return elem.currentStyle[prop]; //IE
}
window.onload = function(){
var d = document.createElement("div"); //Create div
d.className = "layout"; //Set class = "layout"
alert(getStyleProp(d, "color")); //Get property value
}
Regarding comment at your question, another function:
The function below will ignore inline style definitions of the current element. If you want to know the style definitions inherited from a stylesheet (without inherited style definitions of the parent elements), traverse the tree, and temporary wipe the .cssText
property, as shown in the funcion below:
function getNonInlineStyle(elem, prop){
var style = elem.cssText; //Cache the inline style
elem.cssText = ""; //Remove all inline styles
var inheritedPropValue = getStyle(elem, prop); //Get inherited value
elem.cssText = style; //Add the inline style back
return inheritedPropValue;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With