Appearance of any HTML element can be controlled through style attribute of the element. In general, syntax of the HTML style attribute is is written like this:
style=”property:value”
The ‘property’ here refers to a CSS property like display, color or font-family a CSS value.
An example HTML page with styling is shown below. The style element in <p> tag renders the text color within its tag as green.
<html>
<body>
<p style=”color:green”>MY TEXT</p>
</body>
</html>
Styles can be added to HTML elements in following three methods:
- Inline: Using ‘style’ attribute in HTML elements as described above
- Internal: Through <style> element in HTML page’s header section
- External: Using external CSS files
More about applying HTML styles can be found in tutorials HTML/Advanced/CSS and CSS Tutorial.
DOM Level 2 Style Module
The DOM Level 2 Style specifications provided API to access as well as manipulate the style elements of HTML elements across all the methods described above. To determine whether a browser supports or not the DOM Level 2 and 3 for CSS following code may be applied:
Syntax
document.implementation.hasFeature(“CSS”, “2.0”);
document.implementation.hasFeature(“CSS2”, “2.0”);
CSSStyleDeclaration / Style object
The HTMLElement’s style property returns a CSSStyleDeclaration object that represents the chosen element's style attribute. CSSStyleDeclaration represents a collection of CSS property-value pairs.
Properties of CSSStyleDeclaration object
cssText
The cssText property sets or returns the contents of a style declaration as a string.
length
The length property returns a number of CSS properties applied to the element.
parentRule
The parentRule property returns (sets) a CSS Rule object representing the CSS information of the container.
Example with CSSStyleDeclaration object's properties
Methods of CSSStyleDeclaration object
getPropertyPriority(propetyName)
The getPropertyPriority(propetyName) method returns “important” if the given property is set using the !important; value otherwise it returns empty string.
Short example of getPropertyPriority() method
color : “red” !important;
priority = styleObj.getPropertyPriority('color');
getPropertyValue(propertyName)
The getPropertyValue(propertyName) method returns the string value of the given property name.
Item(index)
The Item(index) method fetches the CSS property at a given position.
removeProperty(propertyName)
The removeProperty(propertyName) method removes the property referenced by the propertyName and returns the value deleted.
setProperty(propertyName, value, priority)
The setProperty(propertyName, value, priority) method sets the value for the property with the priority set as an argument.
Example with CSSStyleDeclaration object's methods
Comments
No comments have been made yet.
Please login to leave a comment. Login now