MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  • Setting inline styles
  • Getting inline styles
  • Summary
  1. 2nd Month
  2. Week 6
  3. DOM (Document Object Model)
  4. Manipulating Element’s Styles

JavaScript Style

Setting inline styles

To set the inline style of an element, you use the style property of that element:

element.styleCode language: CSS (css)

The style property returns the read-only CSSStyleDeclaration object that contains a list of CSS properties. For example, to set the color of an element to red, you use the following code:

element.style.color = 'red';Code language: JavaScript (javascript)

If the CSS property contains hyphens (-) for example -webkit-text-stroke you can use the array-like notation ([]) to access the property:

element.style.['-webkit-text-stock'] = 'unset';Code language: JavaScript (javascript)

The following table shows the common CSS properties:

CSS

JavaScript

background

background

background-attachment

backgroundAttachment

background-color

backgroundColor

background-image

backgroundImage

background-position

backgroundPosition

background-repeat

backgroundRepeat

border

border

border-bottom

borderBottom

border-bottom-color

borderBottomColor

border-bottom-style

borderBottomStyle

border-bottom-width

borderBottomWidth

border-color

borderColor

border-left

borderLeft

border-left-color

borderLeftColor

border-left-style

borderLeftStyle

border-left-width

borderLeftWidth

border-right

borderRight

border-right-color

borderRightColor

border-right-style

borderRightStyle

border-right-width

borderRightWidth

border-style

borderStyle

border-top

borderTop

border-top-color

borderTopColor

border-top-style

borderTopStyle

border-top-width

borderTopWidth

border-width

borderWidth

clear

clear

clip

clip

color

color

cursor

cursor

display

display

filter

filter

float

cssFloat

font

font

font-family

fontFamily

font-size

fontSize

font-variant

fontVariant

font-weight

fontWeight

height

height

left

left

letter-spacing

letterSpacing

line-height

lineHeight

list-style

listStyle

list-style-image

listStyleImage

list-style-position

listStylePosition

list-style-type

listStyleType

margin

margin

margin-bottom

marginBottom

margin-left

marginLeft

margin-right

marginRight

margin-top

marginTop

overflow

overflow

padding

padding

padding-bottom

paddingBottom

padding-left

paddingLeft

padding-right

paddingRight

padding-top

paddingTop

page-break-after

pageBreakAfter

page-break-before

pageBreakBefore

position

position

stroke-dasharray

strokeDasharray

stroke-dashoffset

strokeDashoffset

stroke-width

strokeWidth

text-align

textAlign

text-decoration

textDecoration

text-indent

textIndent

text-transform

textTransform

top

top

vertical-align

verticalAlign

visibility

visibility

width

width

z-index

zIndex

To completely override the existing inline style, you set the cssText property of the style object. For example:

element.style.cssText = 'color:red;background-color:yellow';
Code language: JavaScript (javascript)

Or you can use the setAttribute() method:

element.setAttribute('style','color:red;background-color:yellow');Code language: JavaScript (javascript)

Once setting the inline style, you can modify one or more CSS properties:

element.style.color = 'blue';Code language: JavaScript (javascript)

If you do not want to completely overwrite the existing CSS properties, you can concatenate the new CSS property to the cssText as follows:

element.style.cssText += 'color:red;background-color:yellow';Code language: JavaScript (javascript)

In this case, the += operator appends the new style string to the existing one.

The following css() helper function is used to set multiple styles for an element from an object of key-value pairs:

function css(e, styles) {
    for (const property in styles)
        e.style[property] = styles[property];
}Code language: JavaScript (javascript)

You can use this css() function to set multiple styles for an element with the id #content as follows:

let content = document.querySelector('#content');
css(content, { background: 'yellow', border: 'solid 1px red'});Code language: JavaScript (javascript)

The following example uses the style object to set the CSS properties of a paragraph with the id content:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JS Style Demo</title>
</head>
<body>
    <p id="content">JavaScript Setting Style Demo!</p>
    <script>
        let p = document.querySelector('#content');
        p.style.color = 'red';
        p.style.fontWeight = 'bold';
    </script>
</body>
</html>Code language: HTML, XML (xml)

How it works:

  • First, select the paragraph element whose id is content by using the querySelector() method.

  • Then, set the color and font-weight properties of the paragraph by setting the color and fontWeight properties of the style object.

Getting inline styles

The style property returns the inline styles of an element. It is not very useful in practice because the style property doesn’t return the rules that come from elsewhere e.g., styles from an external style sheet.

Summary

  • Use the properties of element.style object to set the inline CSS properties for the HTML element.

PreviousManipulating Element’s StylesNextgetComputedStyle()

Last updated 1 year ago

To get all styles applied to an element, you should use the method.

2️⃣
window.getComputedStyle()