Changing CSS with JavaScript
JavaScript allows you to change the CSS of the HTML element dynamically.
When HTML gets loaded in the browser, it creates a DOM tree. The DOM tree contains each HTML element in the object format. Furthermore, each HTML element object contains the ‘style‘ object as a property. Here, a ‘style‘ object contains various properties like color, backgroundcolor, etc., to change or get the element’s style.
So, you can use various properties of the ‘style‘ object to change the style of the particular HTML element.
Syntax
Follow the syntax below to change the CSS of the HTML element.
element.style.property = value;
In the above syntax, ‘element’ is an HTML element, which you need to access from the DOM tree. The ‘property’ is a CSS property, and the ‘value’ can be static or dynamic.
For example, you can change an element’s background color or font size by setting the corresponding properties on its Style Object. The best usage of this approach is for implementing dynamic behaviors, such as animations, transitions, and real-time updates to the user interface. Let’s see this in practical −
Welcome to TutorialspointSwitch to DarkSwitch to LightIncrease Font SizeDecrease Font Size
Example: Changing the style of the HTML element
We have applied the initial style to the div element in the code below. In JavaScript, we change the div element’s background color using the style object’s ‘backgroundColor’ property.
<!DOCTYPE html><html><head><style>div { background-color: blue; width:700px; height:100px; color: white;}</style></head><body><div id ="square"> Changing the color ofthis Div.</div><br><button onclick="changeColor()"> Change Color </button><script>functionchangeColor(){let square = document.getElementById('square'); square.style.backgroundColor ='red';}</script></body></html></pre>
Changing Style of the Element When Event Triggers
You can also change the style of the element when a particular event triggers.
Example
In the below code, we added the 'click' event to the <div> element. When users click the button, it changes the background color of the div element.
<!DOCTYPE html><html><head><style>div { width:700px; height:100px; color: white; background-color: orange;}</style></head><body><div id ="square"> Click Me </div><br><script>const square = document.getElementById('square'); square.addEventListener('click',()=>{ square.style.backgroundColor ='green'; square.style.fontSize ="25px";});</script></body></html></pre>
Changing CSS of HTML elements Dynamically
You can also change the CSS of the HTML element dynamically. You can assign values using the variables.
Example
We have added the default style to the <div> element in the code below.
Also, we have created multiple radio buttons. When users select any radio button, it changes the style of the div element accordingly.
<!DOCTYPE html><html><head><style> p {width:700px; height:100px; color: white; background-color: blue;}</style></head><body><div><p id ="square">Select any of the following colors to change the background color</p></div><div>Yellow:<input type ="radio" id ="yellow" name ="color"></div><div>Green:<input type ="radio" id ="green" name ="color"></div><div>Red:<input type ="radio" id ="red" name ="color"></div><script>let square = document.getElementById('square');// Changing the style when radio button changeslet colors = document.getElementsByName('color');for(let i =0; i < colors.length; i++){ colors[i].addEventListener('change',function(){ square.style.backgroundColor =this.id;});}</script></body></html></pre>
List of JavaScript DOM Style Object Properties
Following is a list of properties provided by JavaScript DOM Style Object −
Sr.No Properties & Description 1 alignContentIt aligns the flexible container's item on the cross-axis or vertical axis when they do not use all available spaces. 2 alignItemsIt sets the default alignment of items inside a flexible container. 3 alignSelfIt sets the default alignment of a single flex item along the cross axis within a flexible container. 4 animationIt define the desired styles. 5 animationDelayIt sets the delay time in seconds or milliseconds after which animation should start. 6 animationDirectionIt sets the direction of animation. 7 animationDurationIt specifies the time it takes for an animation to complete one cycle. 8 animationFillModeIt specifies the style of an element when the animation is not playing, has ended, or contains a delay. 9 animationIterationCountIt sets or returns the number of times an animation should be played. 10 animationNameIt gets or sets the animation name for @keyframes animation. 11 animationTimingFunctionIt specifies the speed curve of an animation. 12 animationPlayStateIt specifies whether an animation is running or paused. 13 backgroundIt sets or returns up to 8 separate background properties of an element. 14 backgroundAttachmentIt sets or returns whether the background image should scroll with the content or remain fixed. 15 backgroundColorIt sets or returns the background color of an element. 16 backgroundImageIt sets or returns the background image of an element. 17 backgroundPositionIt sets or returns the position of the background image of an element. 18 backgroundRepeatIt sets or returns how a background image is to be repeated. 19 backgroundClipIt sets or returns the painting area of the background. 20 backgroundOriginIt sets or returns the relative position of a background image with respect to padding, border, and content. 21 backgroundSizeIt sets or returns the size of the background image. 22 backfaceVisibilityIt specifies whether the element should be visible or not when it's not facing the screen. 23 borderIt sets or returns the border properties of an element. 24 borderBottomIt sets or returns the border-bottom properties of an element. 25 borderBottomColorIt sets or returns the color of the bottom border of an element. 26 borderBottomLeftRadiusIt sets or returns the radius of the bottom border of the left corner. 27 borderBottomRightRadiusIt sets or returns the radius of the bottom border of the right corner. 28 borderBottomStyleIt sets or returns the border-bottom style of an element. 29 borderBottomWidthIt sets or returns the border-bottom width of the element. 30 borderCollapseIt specifies whether table cell elements should have separate borders or share a single border that is collapsed into a single border. 31 borderColorIt sets or returns the border color of an element. 32 borderImageIt sets or returns the border image of an element. 33 borderImageOutsetIt specifies the border image area amount by which it extends beyond the border box. 34 borderImageRepeatIt sets or returns whether the image border should be rounded, repeated, or stretched. 35 borderImageSliceIt specifies the inward offsets of the image border. 36 borderImageSourceIt sets or returns the source of the image to be used as a border image for an element. 37 borderImageWidthIt sets or returns the width of the image border. 38 borderLeftIt sets or returns the left border properties of an element. 39 borderLeftColorIt sets or returns the color of the left border of an element. 40 borderLeftStyleIt sets or returns the left border style of an element. 41 borderLeftWidthIt sets or returns the left border width of the element. 42 borderRadiusIt sets or returns four different border-radius properties. 43 borderRightIt sets or returns the right border properties of an element. 44 borderRightColorIt sets or returns the color of the right border of an element. 45 borderRightStyleIt sets or returns the right border style of an element. 46 borderRightWidthIt sets or returns the right border width of the element. 47 borderSpacingIt sets or returns the space between cells in the table. 48 borderStyleIt sets or returns the border style of an element. 49 borderTopIt sets or returns the top border properties of an element. 50 borderTopColorIt sets or returns the color of the top border of an element. 51 borderTopLeftRadiusIt sets or returns the border radius of the top left corner. 52 borderTopRightRadiusIt sets or returns the border radius of the top right corner. 53 borderTopStyleIt sets or returns the top border style of an element. 54 borderTopWidthIt sets or returns the top border width of the element. 55 borderWidthIt sets or returns the border width of the element. 56 bottomIt sets or returns the bottom position of a positioned element. 57 boxShadowIt sets or gets the shadow around or inside the element's frame. 58 boxSizingIt specifies the way an element's total width and height is calculated. 59 captionSideIt sets or returns the table caption position. 60 caretColorIt sets or gets the cursor color of any editable element, in inputs or areas. 61 clearIt sets or gets the relative position of a specific element with respect to floating objects. 62 clipIt sets or gets the visible part of a positioned element. 63 colorIt sets or gets the text color of the selected element. 64 columnCountIt specifies the number of columns into which an element should be divided. 65 columnFillIt specifies how contents will be arranged in columns when broken into various columns. 66 columnGapIt specifies the gap between the columns. 67 columnRuleIt sets or returns column rule properties. 68 columnRuleColorIt sets or gets the rule color between columns. 69 columnRuleStyleIt sets or gets the rule style between the columns. 70 columnRuleWidthIt sets or gets the rule width between the columns. 71 columnsIt sets the column Width and column Count. 72 columnSpanIt defines the number of columns on which an element should span across. 73 columnWidthIt sets or gets the width of the columns. 74 counterIncrementIt defines the number of counters to be increased on each occurrence of any selector. 75 counterResetIt creates or resets the Counter. 76 cursorIt sets or gets the type of cursor to be displayed for the mouse pointer. 77 directionIt sets or gets the text direction of an element. 78 displayIt sets or returns the display type of an element. 79 emptyCellsIt sets or gets whether to display or not the border and background property of empty cells. 80 filterIt adds filters or visual effects to an image. 81 flexIt sets or gets whether to display or not the border and background property of empty cells. 82 flexBasisIt sets or returns the initial length of a flexible item. 83 flexDirectionIt sets or returns the direction of placement of flex elements. 84 flexFlowIt specifies the direction of the flexible items and flex-wrap specifies whether the flexible items should be wrapped. 85 flexGrowIt specifies the growth of an item relative to the rest of the flexible items inside the same container. 86 flexShrinkIt specifies how much the item will shrink relative to the rest of the flexible items inside the same container. 87 flexWrapIt specifies whether flexible items should be wrapped. 88 cssFloatIt sets or returns the horizontal alignment of an element. 89 fontIt sets or returns font properties. 90 fontFamilyIt sets or returns a list of font-family names and generic-family names for text in an element. 91 fontSizeIt sets or returns the font size of the text. 92 fontStyleIt sets or returns the font style of an element. 93 fontVariantIt sets or returns texts in small and capital letters. 94 fontWeightIt sets or returns the font-weight property which specifies the thickness of characters in a word. 95 fontSizeAdjustIt sets or returns the font aspect value of the text. 96 heightIt sets or returns the height of an element. 97 isolationIt specifies whether an element must create a new stacking content. 98 justifyContentIt sets or returns the alignment of flex items on the main axis or horizontally when they do not use all the available spaces. 99 leftIt sets or returns the left position of a positioned element. 100 letterSpacingIt sets or returns the space between characters of text. 101 lineHeightIt sets or returns the distance between lines in a text. 102 listStyleIt sets or returns the following three properties. 103 listStylePositionIt positions the list item marker. 104 listStyleImageIt sets an image as a list item marker. 105 listStyleTypeIt sets or gets the marker type of list items. 106 marginIt sets or returns the margins of an element. 107 marginBottomIt sets or returns the bottom margin of an element. 108 marginLeftIt sets or returns the left margin of an element. 109 marginRightIt sets or returns the right margin of an element. 110 marginTopIt sets or returns the top margin of an element. 111 maxHeightIt sets or returns the maximum height of an element. 112 maxWidthIt sets or returns the maximum width of an element. 113 minHeightIt sets or returns the minimum height of an element. 114 minWidthIt sets or returns the minimum width of an element. 115 objectFitIt sets or returns how an image or video is to be resized to fit its container. 116 objectPositionIt defines how an image or video should be positioned in its content box. 117 opacityIt sets or returns the opacity level or transparency level of an element where 0 represents completely transparent and 1 represents not transparent at all. 118 orderIt sets or returns the order of the flexible items relative to flex items in the same container. 119 orphansIt sets or returns the minimum number of lines visible at the bottom of the page for an element. 120 outlineIt sets or returns the following three outline properties. 121 outlineColorIt sets or returns the outline color around an element. 122 outlineOffsetIt sets or returns an outline offset and draws it beyond the border edge. 123 outlineStyleIt sets or returns the outline style around an element. 124 outlineWidthIt sets or returns the outline width of the element. 125 overflowIt decides on what to do with the content which does not fit inside the element box. 126 overflowXIt decides what to do with the left and right edges of content if it does not fit inside the element box. 127 overflowYIt decides what to do with the top and bottom edges of content if it does not fit inside the element box. 128 paddingIt sets or returns the padding of an element. 129 paddingBottomIt sets or returns the bottom padding of an element. 130 paddingLeftIt sets or returns the left padding of an element. 131 paddingRightIt sets or returns the right padding of an element. 132 paddingTopIt sets or returns the top padding of an element. 133 pageBreakAfterIt sets or returns the page break behavior after an element during print or print preview. 134 pageBreakBeforeIt sets or returns the page break behavior before an element during print or print preview. 135 pageBreakInsideIt sets or returns page break behavior inside an element during print or print preview. 136 perspectiveIt specifies the distance that, how far an element is placed from the z=0 plane to provide a 3D view of an element. 137 perspectiveOriginIt sets the position of a 3D element using the x-axis and y-axis. 138 positionIt sets or returns the type of positioning method used on any element. 139 quotesIt sets or returns the type of quotation marks for embedded quotations. 140 resizeIt specifies whether a user can resize or change the height and width of an element or not. 141 rightIt sets or returns the right position of a positioned element including padding, scrollbar, border, and margin. 142 scrollBehaviorIt specifies a smooth scroll effect instead of scrolling instantly when the user clicks on a link within the scrollable box. 143 tableLayoutIt sets or returns the way table cells, rows, and columns are laid out in an HTML document. 144 tabSizeIt sets or returns the length of the space used for the tab character. 145 textAlignIt sets or returns the horizontal alignment of text content inside the block-level element. 146 textAlignLastIt sets or returns the alignment of the last line of text. 147 textDecorationIt sets the textDecorationLine, textDecorationStyle, and the textDecorationColor properties. 148 textDecorationColorIt sets or returns the color of text decoration like overline, underline, and line-through. 149 textDecorationLineIt specifies the type of line the decoration will have. 150 textDecorationStyleIt sets or returns the style of text decoration line like it can be displayed as solid, dashed, dotted, or wavy. 151 textIndentIt sets or returns the indentation of the first line of text. 152 textOverflowIt specifies the behavior of text when it overflows the containing element. 153 textShadowIt sets or returns one or more text-shadow effects. 154 textTransformIt sets or returns the capitalization of text. 155 topIt sets or returns the top position of apositionedelement including margin, border, padding, and scrollbar. 156 transformIt applies a 2D or 3D transformation to transform the object. 157 transformOriginIt allows the user to change the position of transformed elements. 158 transformStyleIt specifies whether child elements are positioned in 3D space or flattened with respect to the plane of the parent element. 159 transitionIt adds an animation-like effect while changing the CSS property of any block-level element when hovered over it. 160 transitionDelayIt sets or returns the delay time in seconds or milliseconds after which the transition effect will start. 161 transitionDurationIt sets or returns the amount of time in seconds or milliseconds, that a transition effect takes to complete. 162 transitionPropertyIt specifies the CSS property name on which the transition effect will be applied. 163 transitionTimingFunctionIt sets or returns the speed curve of the transition effect. 164 unicodeBidiIt specifies how bidirectional text in a document is displayed. 165 userSelectIt sets or returns whether the text can be selected by the user or not. 166 verticalAlignIt sets or returns the vertical alignment of the content in an element. 167 visibilityIt sets or returns whether an element should be visible or not. 168 whiteSpaceIt sets or returns the way how whitespaces are being handled in a text. 169 widthIt sets or returns the width of an element. 170 windowIt sets or returns the minimum number of lines visible at the top of the page for an element. 171 wordBreakIt specifies how words should break when they reach at end of the line except for CJK (Chinese, Japanese, and Korean) scripts. 172 wordSpacingIt sets or returns spacing between words of the sentences. 173 wordWrapIt sets or returns whether long words should be broken to wrap onto the next line. 174 zIndexIt sets the z-order of a positioned element.
Leave a Reply