In this part of JavaScript examples, we have created a simple example which shows the use of style attribute over any element by using the method getElementById().
In the following example, we have created three buttons which calls three different functions addStyleColor() , addStyleHeight() and addStyleWidth() and changes the style property of the specified div with the element's style attribute.
| function addStyleColor() { document.getElementById('myDiv').style.backgroundColor="#ccffdd"; } |
Above line of code defines a function into which specified div's background color is being changed with the help of style attribute.
| function addStyleHeight() { document.getElementById('myDiv').style.height="150px"; } |
Above line of code defines a function into which specified div's height is being changed with the help of style attribute.
| function addStyleWidth() { document.getElementById('myDiv').style.width="250px"; } |
Above line of code defines a function into which specified div's width is being changed with the help of style attribute. Here is the full HTML code as follows :
|
Output :

Click on the button "Style Color". It will call the method addStyleColor() and will change the background color of "myDiv".

Click on the button "Style Height". It will call the method addStyleHeight() and will change the height of "myDiv".

Click on the button "Style Width". It will call the method addStyleWidth() and will change the width of element "myDiv".

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.
Ask Questions? Discuss: JavaScript getElementById Style
Post your Comment