Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Today we’ll review how to use the JavaScript DOM for inline style modifications, CSS class modifications, and get the true style of an element, and get the true width of an element.

directory

  • element.style
  • window.getComputedStyle()
  • element.className
  • element.classList

Set inline styles

We use the element style attribute to manipulate the inline style of elements.

The style property returns a CSSStyleDeclaration read-only object for the CSS property, for example, to set the color of the element to red

element.style.color = 'red';
Copy the code

If it is a CSS property that contains -, such as -webkit-text-stroke, we can use [] to access the property

element.style.['-webkit-text-stock'] = 'unset';
Copy the code

Common CSS properties are shown in the following table

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

If you need to batch override existing inline styles, you can use the cssText attribute

element.style.cssText = 'color:red; background-color:yellow';
Copy the code

Or you can use the setAttribute() method

element.setAttribute('style'.'color:red; background-color:yellow');
Copy the code

After setting, you can also modify the CSS style individually

element.style.color = 'blue';
Copy the code

If you don’t want to overwrite an existing style, you can also append new CSS to it

element.style.cssText += 'color:red; background-color:yellow';
Copy the code

We can also encapsulate a public function that styles elements with CSS by passing in a key-value object

function css(e, styles) {
  for (const property in styles)
    e.style[property] = styles[property];
}
Copy the code

Use CSS () to set styles

let content = document.querySelector('#content');
css(content, { background: 'yellow'.border: 'solid 1px red'});
Copy the code

HTML sample:

<! DOCTYPEhtml>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Style Demo</title>
</head>
<body>
  <p id="content">Use JavaScript to set styles</p>
  <p id="css">Use the CSS () utility function to set styles</p>
  <script>
    / / # 1
    let p = document.querySelector('#content');
    p.style.color = 'red';
    p.style.fontWeight = 'bold';
    
    / / # 2
    function css(e, styles) {
      for (const property in styles)
        e.style[property] = styles[property];
    }
    
    let pcss = document.querySelector('#css');
    css(pcss, { background: 'yellow'.border: 'solid 1px red'});
  </script>
</body>
</html>
Copy the code

Final HTML presentation

Gets an inline style

In theory we can use the style attribute to retrieve inline styles of elements, but in practice it is not often used because style does not return rules from elsewhere, such as the style of the class class.

To get all the styles of an element, use the window.getComputedStyle() method.

getComputedStyle()

GetComputedStyle () is a method of the Window object that returns the style object for the specified element.

Grammar:

let style = window.getComputedStyle(element [,pseudoElement]);
Copy the code

GetComputedStyle () takes two arguments:

  • elementIs the element that specifies the style to return. If it is a different node type, such as a Text node, the method will report an error.
  • pseudoElementSpecifies the pseudo element to match. The default isnull.

For example, if we want to get the style values for all CSS attributes of the hover state A tag, we would pass the :hover argument to the getComputedStyle() method:

let link = document.querySelector('a');
let style = getComputedStyle(link,':hover');
console.log(style);
Copy the code

The return value

The getComputedStyle() method returns a style object that is an instance of the CSSStyleDeclaration object.

example

1) Basic use

<! DOCTYPEhtml>
<html>

<head>
  <meta charset="utf-8">
  <title>JS getComputedStyle() Demo</title>
  <style type="text/css">
    .message {
      background-color: #fff3d4;
      border: solid 1px #f6b73c;
      padding: 20px;
      color: black;
    }
  </style>
</head>
<body>
  <p class="message" style="color:red">This is getComputedStyle () Demo!</p>

  <script>
    let message = document.querySelector('.message');
    let style = getComputedStyle(message);

    console.log('color:', style.color);
    console.log('background color:', style.backgroundColor);
    / / output:
    // color: rgb(255, 0, 0)
    // background color: rgb(255, 243, 212)
  </script>
</body>
</html>
Copy the code

2) Pseudo-element examples

Let’s extract the CSS style from the pseudo-element using the getComputedStyle() method

<html>
<head>
  <title>JavaScript getComputedStyle() Demo</title>
  <style>
    body {
      font: arial, sans-serif;
      font-size: 1em;
      line-height: 1.6;
    }

    p::first-letter {
      font-size: 1.5 em;
      font-weight: normal
    }
  </style>
</head>
<body>
  <p id='main'>Pseudo-element getComputedStyle() Demo</p>
  <script>
    let p = document.getElementById('main');
    let style = getComputedStyle(p, '::first-letter');
    console.log(style.fontSize);
    // Output: 24px
  </script>
</body>
</html>
Copy the code

className

Use the className attribute to manipulate an element’s CSS class

<ul id="menu" class="vertical main">
  <li>Home page</li>
  <li>service</li>
  <li>about</li>
  <li>To contact me</li>
</ul>

<script>
  let menu = document.querySelector('#menu');
  console.log(menu.className);
  // Output: vertical main
</script>
Copy the code

To add a class, use the += operator to add it to an existing class

element.className += newClassName;
Copy the code

To fully override class, you can use the = operator directly

element.className = "class1 class2";
Copy the code

Gets the full class of the element

let classes = element.className;
Copy the code

Of course, the element has another property that is better for manipulating CSS classes, classList.

classList

ClassList Is the CSS class used to manipulate elements.

ClassList is a read-only attribute of an element that returns a collection of CSS classes.

const classes = element.classList;
Copy the code

ClassList is a DOMTokenList object that represents the contents of the element’s class attribute.

Although classList is read-only, you can use various methods to manipulate the classes it contains.

example

1) Get the element’s CSS class

<div id="content" class="main red">JavaScript classList</div>   

<script>
  let div = document.querySelector('#content');
  for (let cssClass of div.classList) {
    console.log(cssClass);
  }
  / / output:
  // main
  // red
</script>
Copy the code

2) Add one or more classes

Use the add() method to add a new class

let div = document.querySelector('#content');
div.classList.add('info');
Copy the code

Adding multiple classes

let div = document.querySelector('#content');
div.classList.add('info'.'visible'.'block');
Copy the code

3) Delete the class

Use the remove() method to remove the class

let div = document.querySelector('#content');
div.classList.remove('visible');
Copy the code

As with the add() method, you can remove multiple classes

let div = document.querySelector('#content');
div.classList.remove('block'.'red');
Copy the code

4) Replace classes

Replace an existing class using the replace() method

let div = document.querySelector('#content');
div.classList.replace('info'.'warning');
Copy the code

5) Determine whether the class exists

Uses contains() to determine whether the specified class exists, returning true if it does, and false if it does.

let div = document.querySelector('#content');
div.classList.contains('warning'); // true
Copy the code

6) Switch classes

If the element’s class contains the specified class name, the toggle() method removes it. If the class does not contain a class name, the toggle() method adds it to the class list.

let div = document.querySelector('#content');
div.classList.toggle('visible');
Copy the code

Gets the width and height of the element

The following image shows a CSS box model containing block elements with content, padding, border, and margin:

To get the width and height of the element containing the padding and border, use the offsetWidth and offsetHeight attributes of the element:

let box = document.querySelector('.box');
let width = box.offsetWidth;
let height = box.offsetHeight;
Copy the code

The figure below shows the offsetWidth and offsetHeight of an element

To get the width and height of an element that contains the padding but not the border, use the clientWidth and clientHeight attributes:

let box = document.querySelector('.box');
let width = box.clientWidth;
let height = box.clientHeight;
Copy the code

The following image shows the clientWidth and clientHeight of an element:

To get the margin of an element, use the getComputedStyle() method

let box = document.querySelector('.box');
let style = getComputedStyle(box);

let marginLeft = parseInt(style.marginLeft);
let marginRight = parseInt(style.marginRight);
let marginTop = parseInt(style.marginTop);
let marginBottom = parseInt(style.marginBottom);
Copy the code

Again, get the border width of the element

let box = document.querySelector('.box');
let style = getComputedStyle(box);

let borderTopWidth = parseInt(style.borderTopWidth) || 0;
let borderLeftWidth = parseInt(style.borderLeftWidth) || 0;
let borderBottomWidth = parseInt(style.borderBottomWidth) || 0;
let borderRightWidth = parseInt(style.borderRightWidth) || 0;
Copy the code

Get the height and width of the window

let width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
let height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
Copy the code

conclusion

Today we reviewed how to use JavaScript DOM to manipulate the inline style of elements. We also shared how to add, delete, change and check the inline style of CSS class. We also shared how to obtain the style of elements, obtain the width and height of elements, margin and border, etc.

If you want to review DOM knowledge with me, wechat search [Xiaoshuai’s programming notes], updated every day