Style of an html element can be set in 2 ways.
- Specify a css class name for the element.
- Set the style inline for the element.
//Method 1:
<p class="boldText">Some text</p>
//Method 2:
<p style="font-weight:bold;">Some text</p>
Therefore using these 2 attributes we can change the style of any html element in the page. The only thing we need to do is get hold of these attributes in JavaScript and manipulate them.Fortunately accessing a DOM element in JavaScript gives us access to all its attributes. What we get is a DOM object which has the attributes of the element as its properties. So we can perform the same operations we do upon objects.
Changing the css class of an element is quite easy.
Suppose you have a p element on the page and a css defined in your css file
<p> This is some text</p>;
.redText { color : red; }
To change or set the class name for this p
var x = document.getElementById('myPara');
x.className = "redText";
and you are done.
className property changes the class of the specified element. You can specify more then one class, just remember to separate them with a whitespace.
x.className = "redText noBorder";
The other method is setting the inline style for the element. Continue reading →