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.No Properties & Description
1 alignContent

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

2 alignItems

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

3 alignSelf

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

4 animation

It define the desired styles.

5 animationDelay

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

6 animationDirection

It sets the direction of animation.

7 animationDuration

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

8 animationFillMode

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

9 animationIterationCount

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

10 animationName

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

11 animationTimingFunction

It specifies the speed curve of an animation.

12 animationPlayState

It specifies whether an animation is running or paused.

13 background

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

14 backgroundAttachment

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

15 backgroundColor

It sets or returns the background color of an element.

16 backgroundImage

It sets or returns the background image of an element.

17 backgroundPosition

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

18 backgroundRepeat

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

19 backgroundClip

It sets or returns the painting area of the background.

20 backgroundOrigin

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

21 backgroundSize

It sets or returns the size of the background image.

22 backfaceVisibility

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

23 border

It sets or returns the border properties of an element.

24 borderBottom

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

25 borderBottomColor

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

26 borderBottomLeftRadius

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

27 borderBottomRightRadius

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

28 borderBottomStyle

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

29 borderBottomWidth

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

30 borderCollapse

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

31 borderColor

It sets or returns the border color of an element.

32 borderImage

It sets or returns the border image of an element.

33 borderImageOutset

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

34 borderImageRepeat

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

35 borderImageSlice

It specifies the inward offsets of the image border.

36 borderImageSource

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

37 borderImageWidth

It sets or returns the width of the image border.

38 borderLeft

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

39 borderLeftColor

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

40 borderLeftStyle

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

41 borderLeftWidth

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

42 borderRadius

It sets or returns four different border-radius properties.

43 borderRight

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

44 borderRightColor

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

45 borderRightStyle

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

46 borderRightWidth

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

47 borderSpacing

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

48 borderStyle

It sets or returns the border style of an element.

49 borderTop

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

50 borderTopColor

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

51 borderTopLeftRadius

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

52 borderTopRightRadius

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

53 borderTopStyle

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

54 borderTopWidth

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

55 borderWidth

It sets or returns the border width of the element.

56 bottom

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

57 boxShadow

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

58 boxSizing

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

59 captionSide

It sets or returns the table caption position.

60 caretColor

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

61 clear

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

62 clip

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

63 color

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

64 columnCount

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

65 columnFill

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

66 columnGap

It specifies the gap between the columns.

67 columnRule

It sets or returns column rule properties.

68 columnRuleColor

It sets or gets the rule color between columns.

69 columnRuleStyle

It sets or gets the rule style between the columns.

70 columnRuleWidth

It sets or gets the rule width between the columns.

71 columns

It sets the column Width and column Count.

72 columnSpan

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

73 columnWidth

It sets or gets the width of the columns.

74 counterIncrement

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

75 counterReset

It creates or resets the Counter.

76 cursor

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

77 direction

It sets or gets the text direction of an element.

78 display

It sets or returns the display type of an element.

79 emptyCells

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

80 filter

It adds filters or visual effects to an image.

81 flex

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

82 flexBasis

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

83 flexDirection

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

84 flexFlow

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

85 flexGrow

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

86 flexShrink

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

87 flexWrap

It specifies whether flexible items should be wrapped.

88 cssFloat

It sets or returns the horizontal alignment of an element.

89 font

It sets or returns font properties.

90 fontFamily

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

91 fontSize

It sets or returns the font size of the text.

92 fontStyle

It sets or returns the font style of an element.

93 fontVariant

It sets or returns texts in small and capital letters.

94 fontWeight

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

95 fontSizeAdjust

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

96 height

It sets or returns the height of an element.

97 isolation

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

98 justifyContent

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

99 left

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

100 letterSpacing

It sets or returns the space between characters of text.

101 lineHeight

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

102 listStyle

It sets or returns the following three properties.

103 listStylePosition

It positions the list item marker.

104 listStyleImage

It sets an image as a list item marker.

105 listStyleType

It sets or gets the marker type of list items.

106 margin

It sets or returns the margins of an element.

107 marginBottom

It sets or returns the bottom margin of an element.

108 marginLeft

It sets or returns the left margin of an element.

109 marginRight

It sets or returns the right margin of an element.

110 marginTop

It sets or returns the top margin of an element.

111 maxHeight

It sets or returns the maximum height of an element.

112 maxWidth

It sets or returns the maximum width of an element.

113 minHeight

It sets or returns the minimum height of an element.

114 minWidth

It sets or returns the minimum width of an element.

115 objectFit

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

116 objectPosition

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

117 opacity

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.

118 order

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

119 orphans

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

120 outline

It sets or returns the following three outline properties.

121 outlineColor

It sets or returns the outline color around an element.

122 outlineOffset

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

123 outlineStyle

It sets or returns the outline style around an element.

124 outlineWidth

It sets or returns the outline width of the element.

125 overflow

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

126 overflowX

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

127 overflowY

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

128 padding

It sets or returns the padding of an element.

129 paddingBottom

It sets or returns the bottom padding of an element.

130 paddingLeft

It sets or returns the left padding of an element.

131 paddingRight

It sets or returns the right padding of an element.

132 paddingTop

It sets or returns the top padding of an element.

133 pageBreakAfter

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

134 pageBreakBefore

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

135 pageBreakInside

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

136 perspective

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

137 perspectiveOrigin

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

138 position

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

139 quotes

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

140 resize

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

141 right

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

142 scrollBehavior

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

143 tableLayout

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

144 tabSize

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

145 textAlign

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

146 textAlignLast

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

147 textDecoration

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

148 textDecorationColor

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

149 textDecorationLine

It specifies the type of line the decoration will have.

150 textDecorationStyle

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

151 textIndent

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

152 textOverflow

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

153 textShadow

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

154 textTransform

It sets or returns the capitalization of text.

155 top

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

156 transform

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

157 transformOrigin

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

158 transformStyle

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

159 transition

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

160 transitionDelay

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

161 transitionDuration

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

162 transitionProperty

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

163 transitionTimingFunction

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

164 unicodeBidi

It specifies how bidirectional text in a document is displayed.

165 userSelect

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

166 verticalAlign

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

167 visibility

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

168 whiteSpace

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

169 width

It sets or returns the width of an element.

170 window

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

171 wordBreak

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

172 wordSpacing

It sets or returns spacing between words of the sentences.

173 wordWrap

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

174 zIndex

It sets the z-order of a positioned element.

Advertisements