Div css class in javascript

Styles and classes

Before we get into JavaScript’s ways of dealing with styles and classes – here’s an important rule. Hopefully it’s obvious enough, but we still have to mention it.

There are generally two ways to style an element:

JavaScript can modify both classes and style properties.

We should always prefer CSS classes to style . The latter should only be used if classes “can’t handle it”.

For example, style is acceptable if we calculate coordinates of an element dynamically and want to set them from JavaScript, like this:

let top = /* complex calculations */; let left = /* complex calculations */; elem.style.left = left; // e.g '123px', calculated at run-time elem.style.top = top; // e.g '456px'

For other cases, like making the text red, adding a background icon – describe that in CSS and then add the class (JavaScript can do that). That’s more flexible and easier to support.

className and classList

Changing a class is one of the most often used actions in scripts.

In the ancient time, there was a limitation in JavaScript: a reserved word like «class» could not be an object property. That limitation does not exist now, but at that time it was impossible to have a «class» property, like elem.class .

Читайте также:  Java api android app

So for classes the similar-looking property «className» was introduced: the elem.className corresponds to the «class» attribute.

   

If we assign something to elem.className , it replaces the whole string of classes. Sometimes that’s what we need, but often we want to add/remove a single class.

There’s another property for that: elem.classList .

The elem.classList is a special object with methods to add/remove/toggle a single class.

   

So we can operate both on the full class string using className or on individual classes using classList . What we choose depends on our needs.

  • elem.classList.add/remove(«class») – adds/removes the class.
  • elem.classList.toggle(«class») – adds the class if it doesn’t exist, otherwise removes it.
  • elem.classList.contains(«class») – checks for the given class, returns true/false .

Besides, classList is iterable, so we can list all classes with for..of , like this:

   

Element style

The property elem.style is an object that corresponds to what’s written in the «style» attribute. Setting elem.style.width=»100px» works the same as if we had in the attribute style a string width:100px .

For multi-word property the camelCase is used:

background-color => elem.style.backgroundColor z-index => elem.style.zIndex border-left-width => elem.style.borderLeftWidth
document.body.style.backgroundColor = prompt('background color?', 'green');

Browser-prefixed properties like -moz-border-radius , -webkit-border-radius also follow the same rule: a dash means upper case.

button.style.MozBorderRadius = '5px'; button.style.WebkitBorderRadius = '5px';

Resetting the style property

Sometimes we want to assign a style property, and later remove it.

For instance, to hide an element, we can set elem.style.display = «none» .

Then later we may want to remove the style.display as if it were not set. Instead of delete elem.style.display we should assign an empty string to it: elem.style.display = «» .

// if we run this code, the will blink document.body.style.display = "none"; // hide setTimeout(() => document.body.style.display = "", 1000); // back to normal

If we set style.display to an empty string, then the browser applies CSS classes and its built-in styles normally, as if there were no such style.display property at all.

Also there is a special method for that, elem.style.removeProperty(‘style property’) . So, We can remove a property like this:

document.body.style.background = 'red'; //set background to red setTimeout(() => document.body.style.removeProperty('background'), 1000); // remove background after 1 second

Normally, we use style.* to assign individual style properties. We can’t set the full style like div.style=»color: red; width: 100px» , because div.style is an object, and it’s read-only.

To set the full style as a string, there’s a special property style.cssText :

This property is rarely used, because such assignment removes all existing styles: it does not add, but replaces them. May occasionally delete something needed. But we can safely use it for new elements, when we know we won’t delete an existing style.

The same can be accomplished by setting an attribute: div.setAttribute(‘style’, ‘color: red. ‘) .

Mind the units

Don’t forget to add CSS units to values.

For instance, we should not set elem.style.top to 10 , but rather to 10px . Otherwise it wouldn’t work:

   

Please note: the browser “unpacks” the property style.margin in the last lines and infers style.marginLeft and style.marginTop from it.

Computed styles: getComputedStyle

So, modifying a style is easy. But how to read it?

For instance, we want to know the size, margins, the color of an element. How to do it?

The style property operates only on the value of the «style» attribute, without any CSS cascade.

So we can’t read anything that comes from CSS classes using elem.style .

For instance, here style doesn’t see the margin:

  body The red text  

…But what if we need, say, to increase the margin by 20px ? We would want the current value of it.

There’s another method for that: getComputedStyle .

getComputedStyle(element, [pseudo])

element Element to read the value for. pseudo A pseudo-element if required, for instance ::before . An empty string or no argument means the element itself.

The result is an object with styles, like elem.style , but now with respect to all CSS classes.

  body   

There are two concepts in CSS:

  1. A computed style value is the value after all CSS rules and CSS inheritance is applied, as the result of the CSS cascade. It can look like height:1em or font-size:125% .
  2. A resolved style value is the one finally applied to the element. Values like 1em or 125% are relative. The browser takes the computed value and makes all units fixed and absolute, for instance: height:20px or font-size:16px . For geometry properties resolved values may have a floating point, like width:50.5px .

A long time ago getComputedStyle was created to get computed values, but it turned out that resolved values are much more convenient, and the standard changed.

So nowadays getComputedStyle actually returns the resolved value of the property, usually in px for geometry.

We should always ask for the exact property that we want, like paddingLeft or marginTop or borderTopWidth . Otherwise the correct result is not guaranteed.

For instance, if there are properties paddingLeft/paddingTop , then what should we get for getComputedStyle(elem).padding ? Nothing, or maybe a “generated” value from known paddings? There’s no standard rule here.

Visited links may be colored using :visited CSS pseudoclass.

But getComputedStyle does not give access to that color, because otherwise an arbitrary page could find out whether the user visited a link by creating it on the page and checking the styles.

JavaScript may not see the styles applied by :visited . And also, there’s a limitation in CSS that forbids applying geometry-changing styles in :visited . That’s to guarantee that there’s no side way for an evil page to test if a link was visited and hence to break the privacy.

Summary

To manage classes, there are two DOM properties:

  • className – the string value, good to manage the whole set of classes.
  • classList – the object with methods add/remove/toggle/contains , good for individual classes.
  • The style property is an object with camelCased styles. Reading and writing to it has the same meaning as modifying individual properties in the «style» attribute. To see how to apply important and other rare stuff – there’s a list of methods at MDN.
  • The style.cssText property corresponds to the whole «style» attribute, the full string of styles.

To read the resolved styles (with respect to all classes, after all CSS is applied and final values are calculated):

Tasks

Create a notification

Write a function showNotification(options) that creates a notification: with the given content. The notification should automatically disappear after 1.5 seconds.

// shows an element with the text "Hello" near the right-top of the window showNotification(< top: 10, // 10px from the top of the window (by default 0px) right: 10, // 10px from the right edge of the window (by default 0px) html: "Hello!", // the HTML of notification className: "welcome" // an additional class for the div (optional) >);

Use CSS positioning to show the element at given top/right coordinates. The source document has the necessary styles.

Источник

JavaScript classList

Summary: in this tutorial, you will learn how to use the JavaScript classList property to work with the CSS classes of an element.

Introduction to JavaScript classList property

The classList is a read-only property of an element that returns a live collection of CSS classes:

const classes = element.classList;Code language: JavaScript (javascript)

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

Even though the classList is read-only, but you can manipulate the classes it contains using various methods.

JavaScript classList examples

Let’s take some examples of manipulating CSS classes of the element via the classList ‘s interface.

1) Get the CSS classes of an element

Suppose that you have a div element with two classes: main and red .

div id="content" class="main red">JavaScript classList div> Code language: HTML, XML (xml)

The following code displays the class list of the div element in the Console window:

let div = document.querySelector('#content'); for (let cssClass of div.classList) < console.log(cssClass); >Code language: JavaScript (javascript)
  • First, select the div element with the id content using the querySelector() method.
  • Then, iterate over the elements of the classList and show the classes in the Console window.

2) Add one or more classes to the class list of an element

To add one or more CSS classes to the class list of an element, you use the add() method of the classList .

For example, the following code adds the info class to the class list of the div element with the id content :

let div = document.querySelector('#content'); div.classList.add('info'); Code language: JavaScript (javascript)

The following example adds multiple CSS classes to the class list of an element:

let div = document.querySelector('#content'); div.classList.add('info','visible','block'); Code language: JavaScript (javascript)

3) Remove element’s classes

To remove a CSS class from the class list of an element, you use the remove() method:

let div = document.querySelector('#content'); div.classList.remove('visible');Code language: JavaScript (javascript)

Like the add() method, you can remove multiple classes once:

let div = document.querySelector('#content'); div.classList.remove('block','red');Code language: JavaScript (javascript)

4) Replace a class of an element

To replace an existing CSS class with a new one, you use the replace() method:

let div = document.querySelector('#content'); div.classList.replace('info','warning');Code language: JavaScript (javascript)

5) Check if an element has a specified class

To check if the element has a specified class, you use the contains() method:

let div = document.querySelector('#content'); div.classList.contains('warning'); // trueCode language: JavaScript (javascript)

The contains() method returns true if the classList contains a specified class; otherwise false .

6) Toggle a class

If the class list of an element contains a specified class name, the toggle() method removes it. If the class list doesn’t contain the class name, the toggle() method adds it to the class list.

The following example uses the toggle() method to toggle the visible class of an element with the id content :

let div = document.querySelector('#content'); div.classList.toggle('visible');Code language: JavaScript (javascript)

Summary

  • The element’s classList property returns the live collection of CSS classes of the element.
  • Use add() and remove() to add CSS classes to and remove CSS classes from the class list of an element.
  • Use replace() method to replace an existing class with a new one.
  • Use contains() method to check if the class list of an element contains a specified class.
  • Use the toggle() method to toggle a class.

Источник

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