JavaScript - 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 −

HTML DOM Style Object

Welcome to Tutorialspoint

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 of this Div. </div> <br>
  <button onclick="changeColor()"> Change Color </button>
  <script>
    function changeColor() {
      let square = document.getElementById('square');
      square.style.backgroundColor = 'red';
    }
  </script>
</body>
</html>

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> 

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 changes
  let 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>

List of JavaScript DOM Style Object Properties

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

Sr.NoProperties & Description
1alignContent

It aligns the flexible container's item on the cross-axis or vertical axis when they do not use all available spaces.

2alignItems

It sets the default alignment of items inside a flexible container.

3alignSelf

It sets the default alignment of a single flex item along the cross axis within a flexible container.

4animation

It define the desired styles.

5animationDelay

It sets the delay time in seconds or milliseconds after which animation should start.

6animationDirection

It sets the direction of animation.

7animationDuration

It specifies the time it takes for an animation to complete one cycle.

8animationFillMode

It specifies the style of an element when the animation is not playing, has ended, or contains a delay.

9animationIterationCount

It sets or returns the number of times an animation should be played.

10animationName

It gets or sets the animation name for @keyframes animation.

11animationTimingFunction

It specifies the speed curve of an animation.

12animationPlayState

It specifies whether an animation is running or paused.

13background

It sets or returns up to 8 separate background properties of an element.

14backgroundAttachment

It sets or returns whether the background image should scroll with the content or remain fixed.

15backgroundColor

It sets or returns the background color of an element.

16backgroundImage

It sets or returns the background image of an element.

17backgroundPosition

It sets or returns the position of the background image of an element.

18backgroundRepeat

It sets or returns how a background image is to be repeated.

19backgroundClip

It sets or returns the painting area of the background.

20backgroundOrigin

It sets or returns the relative position of a background image with respect to padding, border, and content.

21backgroundSize

It sets or returns the size of the background image.

22backfaceVisibility

It specifies whether the element should be visible or not when it's not facing the screen.

23border

It sets or returns the border properties of an element.

24borderBottom

It sets or returns the border-bottom properties of an element.

25borderBottomColor

It sets or returns the color of the bottom border of an element.

26borderBottomLeftRadius

It sets or returns the radius of the bottom border of the left corner.

27borderBottomRightRadius

It sets or returns the radius of the bottom border of the right corner.

28borderBottomStyle

It sets or returns the border-bottom style of an element.

29borderBottomWidth

It sets or returns the border-bottom width of the element.

30borderCollapse

It specifies whether table cell elements should have separate borders or share a single border that is collapsed into a single border.

31borderColor

It sets or returns the border color of an element.

32borderImage

It sets or returns the border image of an element.

33borderImageOutset

It specifies the border image area amount by which it extends beyond the border box.

34borderImageRepeat

It sets or returns whether the image border should be rounded, repeated, or stretched.

35borderImageSlice

It specifies the inward offsets of the image border.

36borderImageSource

It sets or returns the source of the image to be used as a border image for an element.

37borderImageWidth

It sets or returns the width of the image border.

38borderLeft

It sets or returns the left border properties of an element.

39borderLeftColor

It sets or returns the color of the left border of an element.

40borderLeftStyle

It sets or returns the left border style of an element.

41borderLeftWidth

It sets or returns the left border width of the element.

42borderRadius

It sets or returns four different border-radius properties.

43borderRight

It sets or returns the right border properties of an element.

44borderRightColor

It sets or returns the color of the right border of an element.

45borderRightStyle

It sets or returns the right border style of an element.

46borderRightWidth

It sets or returns the right border width of the element.

47borderSpacing

It sets or returns the space between cells in the table.

48borderStyle

It sets or returns the border style of an element.

49borderTop

It sets or returns the top border properties of an element.

50borderTopColor

It sets or returns the color of the top border of an element.

51borderTopLeftRadius

It sets or returns the border radius of the top left corner.

52borderTopRightRadius

It sets or returns the border radius of the top right corner.

53borderTopStyle

It sets or returns the top border style of an element.

54borderTopWidth

It sets or returns the top border width of the element.

55borderWidth

It sets or returns the border width of the element.

56bottom

It sets or returns the bottom position of a positioned element.

57boxShadow

It sets or gets the shadow around or inside the element's frame.

58boxSizing

It specifies the way an element's total width and height is calculated.

59captionSide

It sets or returns the table caption position.

60caretColor

It sets or gets the cursor color of any editable element, in inputs or areas.

61clear

It sets or gets the relative position of a specific element with respect to floating objects.

62clip

It sets or gets the visible part of a positioned element.

63color

It sets or gets the text color of the selected element.

64columnCount

It specifies the number of columns into which an element should be divided.

65columnFill

It specifies how contents will be arranged in columns when broken into various columns.

66columnGap

It specifies the gap between the columns.

67columnRule

It sets or returns column rule properties.

68columnRuleColor

It sets or gets the rule color between columns.

69columnRuleStyle

It sets or gets the rule style between the columns.

70columnRuleWidth

It sets or gets the rule width between the columns.

71columns

It sets the column Width and column Count.

72columnSpan

It defines the number of columns on which an element should span across.

73columnWidth

It sets or gets the width of the columns.

74counterIncrement

It defines the number of counters to be increased on each occurrence of any selector.

75counterReset

It creates or resets the Counter.

76cursor

It sets or gets the type of cursor to be displayed for the mouse pointer.

77direction

It sets or gets the text direction of an element.

78display

It sets or returns the display type of an element.

79emptyCells

It sets or gets whether to display or not the border and background property of empty cells.

80filter

It adds filters or visual effects to an image.

81flex

It sets or gets whether to display or not the border and background property of empty cells.

82flexBasis

It sets or returns the initial length of a flexible item.

83flexDirection

It sets or returns the direction of placement of flex elements.

84flexFlow

It specifies the direction of the flexible items and flex-wrap specifies whether the flexible items should be wrapped.

85flexGrow

It specifies the growth of an item relative to the rest of the flexible items inside the same container.

86flexShrink

It specifies how much the item will shrink relative to the rest of the flexible items inside the same container.

87flexWrap

It specifies whether flexible items should be wrapped.

88cssFloat

It sets or returns the horizontal alignment of an element.

89font

It sets or returns font properties.

90fontFamily

It sets or returns a list of font-family names and generic-family names for text in an element.

91fontSize

It sets or returns the font size of the text.

92fontStyle

It sets or returns the font style of an element.

93fontVariant

It sets or returns texts in small and capital letters.

94fontWeight

It sets or returns the font-weight property which specifies the thickness of characters in a word.

95fontSizeAdjust

It sets or returns the font aspect value of the text.

96height

It sets or returns the height of an element.

97isolation

It specifies whether an element must create a new stacking content.

98justifyContent

It sets or returns the alignment of flex items on the main axis or horizontally when they do not use all the available spaces.

99left

It sets or returns the left position of a positioned element.

100letterSpacing

It sets or returns the space between characters of text.

101lineHeight

It sets or returns the distance between lines in a text.

102listStyle

It sets or returns the following three properties.

103listStylePosition

It positions the list item marker.

104listStyleImage

It sets an image as a list item marker.

105listStyleType

It sets or gets the marker type of list items.

106margin

It sets or returns the margins of an element.

107marginBottom

It sets or returns the bottom margin of an element.

108marginLeft

It sets or returns the left margin of an element.

109marginRight

It sets or returns the right margin of an element.

110marginTop

It sets or returns the top margin of an element.

111maxHeight

It sets or returns the maximum height of an element.

112maxWidth

It sets or returns the maximum width of an element.

113minHeight

It sets or returns the minimum height of an element.

114minWidth

It sets or returns the minimum width of an element.

115objectFit

It sets or returns how an image or video is to be resized to fit its container.

116objectPosition

It defines how an image or video should be positioned in its content box.

117opacity

It sets or returns the opacity level or transparency level of an element where 0 represents completely transparent and 1 represents not transparent at all.

118order

It sets or returns the order of the flexible items relative to flex items in the same container.

119orphans

It sets or returns the minimum number of lines visible at the bottom of the page for an element.

120outline

It sets or returns the following three outline properties.

121outlineColor

It sets or returns the outline color around an element.

122outlineOffset

It sets or returns an outline offset and draws it beyond the border edge.

123outlineStyle

It sets or returns the outline style around an element.

124outlineWidth

It sets or returns the outline width of the element.

125overflow

It decides on what to do with the content which does not fit inside the element box.

126overflowX

It decides what to do with the left and right edges of content if it does not fit inside the element box.

127overflowY

It decides what to do with the top and bottom edges of content if it does not fit inside the element box.

128padding

It sets or returns the padding of an element.

129paddingBottom

It sets or returns the bottom padding of an element.

130paddingLeft

It sets or returns the left padding of an element.

131paddingRight

It sets or returns the right padding of an element.

132paddingTop

It sets or returns the top padding of an element.

133pageBreakAfter

It sets or returns the page break behavior after an element during print or print preview.

134pageBreakBefore

It sets or returns the page break behavior before an element during print or print preview.

135pageBreakInside

It sets or returns page break behavior inside an element during print or print preview.

136perspective

It specifies the distance that, how far an element is placed from the z=0 plane to provide a 3D view of an element.

137perspectiveOrigin

It sets the position of a 3D element using the x-axis and y-axis.

138position

It sets or returns the type of positioning method used on any element.

139quotes

It sets or returns the type of quotation marks for embedded quotations.

140resize

It specifies whether a user can resize or change the height and width of an element or not.

141right

It sets or returns the right position of a positioned element including padding, scrollbar, border, and margin.

142scrollBehavior

It specifies a smooth scroll effect instead of scrolling instantly when the user clicks on a link within the scrollable box.

143tableLayout

It sets or returns the way table cells, rows, and columns are laid out in an HTML document.

144tabSize

It sets or returns the length of the space used for the tab character.

145textAlign

It sets or returns the horizontal alignment of text content inside the block-level element.

146textAlignLast

It sets or returns the alignment of the last line of text.

147textDecoration

It sets the textDecorationLine, textDecorationStyle, and the textDecorationColor properties.

148textDecorationColor

It sets or returns the color of text decoration like overline, underline, and line-through.

149textDecorationLine

It specifies the type of line the decoration will have.

150textDecorationStyle

It sets or returns the style of text decoration line like it can be displayed as solid, dashed, dotted, or wavy.

151textIndent

It sets or returns the indentation of the first line of text.

152textOverflow

It specifies the behavior of text when it overflows the containing element.

153textShadow

It sets or returns one or more text-shadow effects.

154textTransform

It sets or returns the capitalization of text.

155top

It sets or returns the top position of apositionedelement including margin, border, padding, and scrollbar.

156transform

It applies a 2D or 3D transformation to transform the object.

157transformOrigin

It allows the user to change the position of transformed elements.

158transformStyle

It specifies whether child elements are positioned in 3D space or flattened with respect to the plane of the parent element.

159transition

It adds an animation-like effect while changing the CSS property of any block-level element when hovered over it.

160transitionDelay

It sets or returns the delay time in seconds or milliseconds after which the transition effect will start.

161transitionDuration

It sets or returns the amount of time in seconds or milliseconds, that a transition effect takes to complete.

162transitionProperty

It specifies the CSS property name on which the transition effect will be applied.

163transitionTimingFunction

It sets or returns the speed curve of the transition effect.

164unicodeBidi

It specifies how bidirectional text in a document is displayed.

165userSelect

It sets or returns whether the text can be selected by the user or not.

166verticalAlign

It sets or returns the vertical alignment of the content in an element.

167visibility

It sets or returns whether an element should be visible or not.

168whiteSpace

It sets or returns the way how whitespaces are being handled in a text.

169width

It sets or returns the width of an element.

170window

It sets or returns the minimum number of lines visible at the top of the page for an element.

171wordBreak

It specifies how words should break when they reach at end of the line except for CJK (Chinese, Japanese, and Korean) scripts.

172wordSpacing

It sets or returns spacing between words of the sentences.

173wordWrap

It sets or returns whether long words should be broken to wrap onto the next line.

174zIndex

It sets the z-order of a positioned element.