Changing CSS

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;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="square"&gt; Changing the color ofthis Div.&lt;/div&gt;&lt;br&gt;&lt;button onclick="changeColor()"&gt; Change Color &lt;/button&gt;&lt;script&gt;functionchangeColor(){let square = document.getElementById('square');
  square.style.backgroundColor ='red';}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div id ="square"&gt; Click Me &lt;/div&gt;&lt;br&gt;&lt;script&gt;const square = document.getElementById('square');
square.addEventListener('click',()=&gt;{
  square.style.backgroundColor ='green';
  square.style.fontSize ="25px";});&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</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;}&lt;/style&gt;&lt;/head&gt;&lt;body&gt;&lt;div&gt;&lt;p id ="square"&gt;Select any of the following colors to change the background color&lt;/p&gt;&lt;/div&gt;&lt;div&gt;Yellow:&lt;input type ="radio" id ="yellow" name ="color"&gt;&lt;/div&gt;&lt;div&gt;Green:&lt;input type ="radio" id ="green" name ="color"&gt;&lt;/div&gt;&lt;div&gt;Red:&lt;input type ="radio" id ="red" name ="color"&gt;&lt;/div&gt;&lt;script&gt;let square = document.getElementById('square');//    Changing the style when radio button changeslet colors = document.getElementsByName('color');for(let i =0; i &lt; colors.length; i++){
colors[i].addEventListener('change',function(){
  square.style.backgroundColor =this.id;});}&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;</pre>

List of JavaScript DOM Style Object Properties

Following is a list of properties provided by JavaScript DOM Style Object −

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *