Javascript dom set style

JavaScript Style

Summary: in this tutorial, you will learn how to use the style property to manipulate the inline style of the HTML elements.

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.

Читайте также:  Как вывести messagebox python

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 :

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)
  • 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.

To get all styles applied to an element, you should use the window.getComputedStyle() method.

Summary

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

Источник

HTMLElement: style property

The read-only style property of the HTMLElement returns the inline style of an element in the form of a live CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned only for the attributes that are defined in the element’s inline style attribute.

Shorthand properties are expanded. If you set style=»border-top: 1px solid black» , the longhand properties ( border-top-color , border-top-style , and border-top-width ) are set instead.

This property is read-only, meaning it is not possible to assign a CSSStyleDeclaration object to it. Nevertheless, it is possible to set an inline style by assigning a string directly to the style property. In this case the string is forwarded to CSSStyleDeclaration.cssText . Using style in this manner will completely overwrite all inline styles on the element.

Читайте также:  Css input not class

Therefore, to add specific styles to an element without altering other style values, it is generally preferable to set individual properties on the CSSStyleDeclaration object. For example, you can write element.style.backgroundColor = «red» .

A style declaration is reset by setting it to null or an empty string, e.g., elt.style.color = null .

Note: CSS property names are converted to JavaScript identifier with these rules:

  • If the property is made of one word, it remains as it is: height stays as is (in lowercase).
  • If the property is made of several words, separated by dashes, the dashes are removed and it is converted to camelCase: background-attachment becomes backgroundAttachment .
  • The property float , being a reserved JavaScript keyword, is converted to cssFloat .

The style property has the same priority in the CSS cascade as an inline style declaration set via the style attribute.

Value

Examples

Getting style information

The following code snippet demonstrates how the values obtained using the element’s style property relates to the style set on the HTML attribute:

doctype html> html lang="en-US"> body style="font-weight:bold"> div style="border-top: 1px solid blue; color:red" id="elt"> An example div div> pre id="out">pre> body> html> 
const element = document.getElementById("elt"); const out = document.getElementById("out"); const elementStyle = element.style; // We loop through all styles (for…of doesn't work with CSStyleDeclaration) for (const prop in elementStyle)  if (Object.hasOwn(elementStyle, prop))  out.textContent += `$ elementStyle[prop] > = '$elementStyle.getPropertyValue(elementStyle[prop])>'\n`; > > 

Note font-weight is not listed as a value for elementStyle as it is not defined within the style attribute of the element itself. Rather, it is inherited from the definition on its parent. Also note that the shorthand border-top property, defined in the style attribute, is not listed directly. Rather, it is replaced by the three corresponding longhand properties ( border-top-color , border-top-style , and border-top-width ).

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How to Add Styles to an Element

Summary: in this tutorial, you’ll learn how to add styles to an element using JavaScript DOM methods.

Suppose that you have a element as follows:

div class="note">JavaScript CSS div>Code language: HTML, XML (xml)

And you want to add styles to this element. By using the JavaScript DOM methods, you can add the inline styles or global styles to the element.

Inline styles

To add inline styles to an element, you follow these steps:

  • First, select the element by using DOM methods such as document.querySelector() . The selected element has the style property that allows you to set the various styles to the element.
  • Then, set the values of the properties of the style object.

The following code changes the background color and color of the element above:

const note = document.querySelector('.note'); note.style.backgroundColor = 'yellow'; note.style.color = 'red';Code language: JavaScript (javascript)

1) Using cssText property

Adding individual style is quite verbose. Fortunately, you can add set multiple styles at once by using the cssText property:

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

In this example, we used the += operator to append new styles to the existing ones. If you use the = operator, the existing style will be removed, like this:

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

2) Using a helper function

The following helper function accepts an element and a style object. It add all styles from the style object to the style property of the element :

function css(element, style) < for (const property in style) element.style[property] = style[property]; >Code language: JavaScript (javascript)

And you can use this css() helper function to set the styles for the element as follows:

const note = document.querySelector('.note'); css(note, < 'background-color': 'yellow', color: 'red' >);Code language: JavaScript (javascript)

Global Styles

To add the global styles to an element, you create the style element, fill it with the CSS rules, and append the style element to the DOM tree, like this:

const style = document.createElement('style'); style.innerHTML = ` .note < background-color: yellow; color:red; >`; document.head.appendChild(style);Code language: JavaScript (javascript)

Источник

Оцените статью