In this article, we'll look at various methods for working with element classes and styles. Let's get acquainted with the classList and style properties, and examples of their use to manage the classes and styles of elements on the page, respectively.

Managing element class(es)

The first way to interact with element classes is to use the className DOM property. This property is a reflection of the class attribute in the DOM. The DOM property className was not named class due to the fact that previously in JavaScript, reserved words could not be used to name properties of objects. If you don’t know what DOM properties are and how they differ from attributes, then you can read about it in this article.

An example in which we will perform various operations on an element class using the DOM property className:

var elem = document.querySelector("#alert"); // add a class to the element elem.className = "alert"; // "alert" // change the class of the element elem.className = "alert-warning"; // "alert-warning" // get the class value and store it in className var classElem = elem.className; // "alert-warning" // remove the class from the element elem.className = ""; // ""

The second way to perform operations associated with an element's class is to use methods to manipulate attributes.

An example in which we will perform the same actions as the above code, but using methods to manage attributes:

var elem = document.querySelector("#alert"); // add a class to the element elem.setAttribute("class", "alert"); // change the class of the element elem.setAttribute("class", "alert-warning"); // get the class value and store it in className var classElem = elem.getAttribute("class"); // "alert-warning" // remove the class from the element elem.removeAttribute("class");

The DOM property className and the class attribute are always synchronized with each other, which means that when one changes, the other also changes.

But an element can have more than one class, but several. In this case, working with them as a string is not very convenient.

For example, determining the presence of any one specific class in an element using the above methods can no longer be done so simply. This will require writing some code.

An example in which we check whether an element has the content__show class:

... var elem = document.querySelector("#content"); if ((" " + elem.className + " ").indexOf(" content__show ") > -1) ( // the element has the content__show class) else ( // the element does not have the content__show class)

But besides this situation, there are others. For example, when you need to add one specific class to an element, or remove it. To perform these and other actions very simply, the element has a DOM property classList special for these cases.

classList property

The classList property is a special object (DOMTokenList) that contains methods for performing various operations on the element's classes.

classList methods:

  • .add(className1[,className2,...]) - adds one or more specified classes to the element. If an element already has this class, it will not be added to it.
  • .remove(className1[,className2,... ]) - removes one or more specified classes from an element. If the element does not have the class you want to remove, then no action will be taken.
  • .contains(className) – checks whether an element has a class; returns true or false as a response.
  • .toggle(className [,flag]) - toggles the specified class name of the element, i.e. if the element has this class, then removes it; otherwise adds. The second parameter (flag) is optional. By default it is undefined. If you set it to true or false , it will work like the add or remove method, i.e. either add a class to an element or remove one from it.

An example that shows how you can perform various actions related to element classes using classList methods:

// get the element with id = "sidebar" var sideBar = document.querySelector("#sidebar"); // switch the element's hidden-xs class, i.e. if the element has it, then remove it; and if this class does not exist, then add it to it sideBar.classList.toogle("hidden-xs"); // add three additional classes to the sideBar element.classList.add("col-xs-6","col-sm-4","col-md-3"); // remove the hidden-xs class from the sideBar element.classList.remove("hidden-xs"); // check whether the element has a hidden-lg class and if so, add another hidden-md to it if (sideBar.classList.contains("hidden-lg") ( myID.classList.add("hidden-md" ); )

The classList object is a pseudo-array, i.e. it can be iterated as an array.

An example in which we will iterate over all classes of classList:

... var content = document.querySelector(".content"); // Option No. 1. Using the for loop // classList.length - the number of classes for an element // the classes in classList are counted from 0 for (var i = 0, length = content.classList.length; i< length; i++) { // i - индекс класса в classList // выведем класс в консоль console.log(content.classList[i]); // или так (с помощью метода item) console.log(content.classList.item(i)); } // если мы хотим получить класс по его индексу, а указали в качестве значения индекса число, которое больше, чем (количества элементов - 1) в classList (т.к. отсчет ведётся с 0), то в этом случае получим в качестве результата undefined console.log(content.classList); // undefined // Вариант №2. С помощью цикла for..of for (let className of content.classList) { // выведем класс в консоль console.log(className); }

The classList property is supported by all modern browsers. If you need support for very old browsers (for example, Internet Explorer 8, 9), then in this case you can use some kind of polyfill.

Element styles

In the DOM, every element has a style property with which we can control its styles. The value of this property is a read-only object. Setting styles for an element in this case is done by adding appropriate properties to it.

An example of how you can add styles to an element via the DOM style property:

Square var square = document.querySelector(".square"); square.style.width = "170px"; square.style.height = "170px"; square.backgroundColor = "green";

The names of the properties of the style object are usually the same as the names of the CSS properties. The only exceptions are those CSS properties that use a hyphen. For example, background-color . In this case, the hyphen and the letter following it are replaced with capital ones. For example, the CSS background-color property for a style object would be specified as backgroundColor . And, for example, a CSS property with a browser prefix -webkit-border-radius - like WebkitBorderRadius.

Removing styles

For example, let's set the body to some background color:

Document.body.style.backgroundColor = "#eee";

If we now need to remove this style, then to do this we must simply assign it an empty string:

Document.body.style.backgroundColor = "";

Examples of using the DOM style property to set styles for elements.

// set the text color to red for the element with id = "introtext" using style document.querySelector("#introtext").style.color = "red"; // set all p elements on the page using style to set the text color to green var paragraphs = document.querySelectorAll("p"); for (var i = 0, length = paragraphs.length; i< length; i++) { paragraphs[i].style.backgroundColor = "green"; } // выведем в консоль все CSS свойства элемента с идентификатором "introtext" var styleElem = document.querySelector("#introtext").style; for (var i = 0, length = styleElem.length; i < length; i++) { console.log(styleElem[i]); }

cssText property

In addition to individually setting styles for an element, we can set them immediately using the special property style.cssText . This is done by assigning this property a string consisting of a set of styles separated by a semicolon. Those. This is done in a similar way to how we set styles in the HTML style attribute.

An example in which we set the styles "font-size:40px; color:blue;" elements with the intro class:

//get elements with the intro class var intro = document.querySelectorAll("intro"); //set "font-size:40px; color:blue;" all elements in the collection contained in intro for (var i = 0, length = intro.length; i< length; i++) { intro[i].style.cssText = "font-size:40px; color:blue;"; }

You need to be careful when setting styles using the style.cssText property. This is due to the fact that when set, this property removes all styles that the element has. Those. those that we set for it using the style attribute and in its corresponding DOM property.

You can also perform an operation similar to that performed by the style.cssText property using the setAttribute method.

For example:

//get the first element with the intro class var info = document.querySelector("info"); //set it to the style "margin: 10px; padding: 10px; border: 1px solid green;" info.setAttribute("style", "margin: 10px; padding: 10px; border: 1px solid green;");

Tasks

1. Write a script using classList to assign three classes to an element with the text class: size-40 , color-red and bg-yellow:

.size-40 ( font-size: 40px; ) .color-red ( color: red; ) .bg-yellow ( background: yellow; )

Some text...

2. Write code to set the style "width: 180px; height: 180px;" all elements on the page with a class starting with the words block- .

Hi all! In this article we will look at how to set styles in javascript correctly and cross-browser.

So, those of you who are already at least a little familiar with javascript know that elements have a style property, which stores an object, using which you can set certain CSS styles. However, not everything is as simple as it might seem at first glance. And that's why. Let's create two very ordinary div blocks, but for one we will set styles through the style attribute, and for the other through the style tag.


div(
width: 150px;
height: 150px;
}

#div1 (
background: #f00;
}


Now let's try to display the value of the background property for these blocks.

Var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
alert(div1.style.background);
alert(div2.style.background);

In the first case, we will not receive anything, but for the div2 block the styles will be displayed. Why? The thing is that javascript can only display the values ​​of those properties that were set directly in the html markup using the style attribute, and those that were set via javascript. If we now set the background property like this

Div1.style.background = "#f00";

Now the value will be displayed via alert .

Alert(div1.style.background);

The same styles that we set in the style tag or in an external style sheet are called "computed styles" or "calculated styles". They got this name for a reason. The thing is that the browser first reads the html markup, and then calculates the styles that we set in the external style sheet and applies them to this markup.

However, we can still access them. The DOM Level2 specification has a special function getComputedStyle() for this. Let's see how it works.

Var styles = getComputedStyle(div1);
alert(styles.background);

You must pass it the element whose styles you want to get, and it will return an object to you. Now just specify the property you need, and you will immediately get its value.

However, this feature does not work with older browsers (IE8- ), so if you want your code to be cross-browser compatible, then use the code below.

Function getStyle(element) (
return window.getComputedStyle ? getComputedStyle(element) : element.currentStyle;
}

Similar usage

Var styles = getStyle(div1); alert(styles.background);

So, today we learned how to work with styles in javascript and how to get styles cross-browser.

Abstract: Access to style sheets. Style sheet properties. Adding and removing rules. Changing element styles. Element class names.

Let's consider (for now) a theoretical example - let's say there is a website where a series of technical articles is presented. We want to highlight some of these articles with a cool animated carousel, but what about users who don't have JavaScript enabled for some reason? Recalling what we've learned about unobtrusive JavaScript, we want the Web site's functionality to work for those users as well, but we may want to design the site differently for those users so that they can use the site comfortably, even without a carousel.

If you want to delete this rule, you can call the stylesheet.deleteRule(index) function, where index will be the index of the rule that will be deleted.

In the example of demonstrating articles, you can create a rule that makes the display property equal to none for all articles about HTML and JavaScript - look at the carousel example (http://dev.opera.com/articles/view/dynamic-style-css-javascript/carousel .html) to see it in action.

Note: IE does not implement rules according to standards. It uses rules instead of the cssRules attribute. IE also uses removeRule instead of deleteRule and addRule( selector , rule, index) instead of insertRule .

Changing Element Styles

You should now understand how to edit style sheets associated with a page and create and modify CSS rules within them. What if you want to change a specific element in the DOM? Using the DOM API you can access specific page elements. Returning to the carousel example, you can see that the functions are defined in such a way that when you click on an article, that article is highlighted, while the main text of the article is displayed below.

Using the DOM, we access the style object, which describes the style of the document. This style object is defined as CSSStyleDeclaration; A detailed explanation of this can be found in the W3C documentation on the CSSStyleDeclaration interface (http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSStyleDeclaration). The style object doesn't work quite the same way as some of the other properties defined on the HTML element. Unlike element.href or element.id which return strings, element.style returns an object. This means that it is not possible to set a style by assigning a string to element.style .

The style object has attributes that correspond to various specified CSS properties. For example, style.color returns the color specified on the element. Doing element.style.color = "red"; You can dynamically change the style. Below is a function that turns an element's color red when passed the element's id.

function colorElementRed(id) ( var el = document.getElementById(id); el.style.color = "red"; )

You can also use setAttribute(key, value) to style an element. For example, set the color of an element to red by calling element.setAttribute("style", "color: red"); , but be careful as this removes any changes made to the style object.

When an element's style is specified this way, it is the same as if we specified it as a declaration of the style attribute of an html element. This style will only be applied when the importance and specificity of the rule is greater than other rules applied to the element (specificity is explained in Chapter 28 on CSS Inheritance and Cascading).

Some of you may be wondering what happens when a given CSS property has a hyphen. In this case

Interoperability between JavaScript and CSS

Cascading Style Sheets (CSS) are a standard for the visual presentation of HTML documents. Cascading style sheets are designed for use by designers: they allow you to precisely define fonts, colors, margins, alignment, border options, and even the coordinates of elements in a document.

But they are also of interest to programmers writing in client-side JavaScript because they allow animation effects, such as document contents fading out from the right edge, for example, or lists collapsing and expanding, allowing the user to control how much content is displayed. information.

Managing Inline Styles

The easiest way to control CSS styles is to manipulate the style attribute of individual document elements. Like most HTML attributes, the style attribute corresponds to a property of the same name on the Element object and can be manipulated in JavaScript scripts. However, the style property has one distinctive feature: its value is not a string, but a CSSStyleDeclaration object. The properties of this object represent the CSS properties defined in the HTML style attribute.

For example, to display the contents of a text element e in a large, bold, blue font, you can do the following to write the desired values ​​to properties that correspond to the font-size, font-weight, and color style properties:

E.style.fontSize = "24px"; e.style.fontWeight = "bold"; e.style.color = "blue";

When working with the style properties of a CSSStyleDeclaration object, remember that all values ​​must be specified as strings. In a style sheet or style attribute you can write:

Position: absolute; font-family: sans-serif; background-color: #ffffff;

To do the same for the e element in JavaScript, you need to enclose all values ​​in quotes:

E.style.position = "absolute"; e.style.fontFamily = "sans-serif"; e.style.backgroundColor = "#ffffff";

Note that semicolons are not included in string values. These are semicolons used in JavaScript syntax. The semicolons used in CSS style sheets are not needed in string values ​​set using JavaScript.

Also, remember that all positioning properties must include units of measure. That is:

E.style.left = 300; // Incorrect: this is a number, not a string e.style.left = "300"; // Incorrect: missing units e.style.left = "300px"; // Right

Units are required when setting style properties in JavaScript - the same as when setting style properties in style sheets.

Many CSS style properties, such as font-size, contain a hyphen in their names. JavaScript interprets a hyphen as a minus sign, so the following expression cannot be written:

E.style.font-size = "24px"; // Syntax error!

Thus, the names of the properties of the CSSStyleDeclaration object are slightly different from the names of the actual CSS properties. If a CSS property name contains hyphens, the CSSStyleDeclaration object's property name is formed by removing the hyphens and capitalizing the letter immediately following each one. In other words, the border-left-width CSS property is accessed through the borderLeftWidth property, and the font-family CSS property can be accessed through the fontFamily property.

Additionally, when a CSS property, such as float, has a name that matches a JavaScript reserved word, the name is prefixed with "css" to create a valid CSSStyleDeclaration object property name. That is, to read or change the value of an element's CSS float property, you should use the cssFloat property of the CSSStyleDeclaration object.

An HTML element's style attribute is its inline style, and it overrides any style rules in the CSS sheet. Inline styles are generally convenient to use for setting style values, and this is the approach used in all the examples above. Scripts can read the properties of a CSSStyleDeclaration object representing inline styles, but they return meaningful values ​​only if they were previously set by a JavaScript script or if the HTML element has an inline style attribute that sets the desired properties.

For example, a document might include a style sheet that sets the left margin for all paragraphs to 30 pixels, but reading the leftMargin property of one of these elements will return an empty line unless that paragraph has a style attribute that overrides the value set by the style sheet.

Reading an element's inline style is particularly challenging when reading style properties that have units and shorthand notation properties: the script must include a sophisticated implementation of CSS style string parsing to allow the values ​​to be extracted and used. In general, the inline element style is convenient to use only for setting styles.

Sometimes it is easier to read or write a single line into an element's inline style than to access the CSSStyleDeclaration object. To do this, you can use the getAttribute() and setAttribute() methods of the Element object or the cssText property of the CSSStyleDeclaration object:

// Both statements below set the style attribute // of element e to the string s: e.setAttribute("style", s); e.style.cssText = s; // Both statements below get the value of the e element's style attribute // as a string: s = e.getAttribute("style"); s = e.style.cssText;

Creating Animation Effects Using CSS

One of the most common uses of CSS is in rendering visual animation effects. You can implement them using the setTimeout() or setInterval() methods, using them to organize multiple calls to a function that changes the inline style of an element.

// Makes element e relatively positionable and moves it left and right. // The first argument can be the element object or the value of the id attribute of the // desired element. If you pass a function as the second argument, it will be called with e // as an argument when the animation finishes playing. The third argument determines // the offset value of the element e. Defaults to 5 pixels. // The fourth argument determines how long the effect should play. // By default the effect lasts 500ms. function shake(e, oncomplete, distance, time) ( // Process arguments if (typeof e === "string") e = document.getElementByld(e); if (!time) time = 500; if (!distance) distance = 5; var originalStyle = e.style.cssText; // Keep original style e e.style.position = "relative"; // Make relative positionable var start = (new Date()).getTime(); / / Remember the moment the animation starts animate(); // Start the animation // This function checks the elapsed time and changes the coordinates of e. // If it is time to end the animation, it restores the initial state // of the element e. Otherwise, it changes the coordinates of e and schedules its next call. function animate() ( var now = (new Date()).getTime(); // Get the current time var elapsed = now-start; // How much time has passed since the beginning? var fraction = elapsed / time; // Fraction of required time? if (fraction

Both shake() and fadeOut() take an optional callback function as their second argument. If this function is specified, it will be called when the animation effect has finished playing. The element to which the animation effect was applied will be passed to the callback function as an argument. The following HTML markup creates a button that, when clicked, produces a shake effect and then a dissolve effect:

Click me!

Notice how similar the shake() and fadeOut() functions are to each other. They both can serve as templates for implementing similar animation effects using CSS properties.

Computed Styles

The element's style property specifies the element's inline style. It has an advantage over all style sheets and can be successfully used to set CSS properties to change the visual appearance of an element. However, in general there is no point in calling it when you want to know the actual styles applied to an element. What is required in this case is called computed style.

An element's computed style is the set of property values ​​that the browser has obtained (or calculated) from the inline style and all the rules from all style sheets that apply to the element: it is the set of properties actually used when rendering the element. Like inline styles, computed styles are represented by a CSSStyleDeclaration object. However, unlike inline styles, computed styles are read-only. These styles cannot be changed, but the computed CSSStyleDeclaration object allows you to know exactly the values ​​of the style properties that the browser used when rendering the corresponding element.

You can get the computed style of an element using the getComputedStyle() method of the Window object. The first argument to this method is the element whose calculated style you want to return. The second argument is required and usually passes null or the empty string, but it can also pass a string with a CSS pseudo-element name such as "::before", "::after", ":first-line" or " :first-letter":

Var title = document.getElementById("section1title"); var titlestyles = window.getComputedStyle(element, null);

The return value of the getComputedStyle() method is a CSSStyleDeclaration object representing all styles applied to the specified element (or pseudo-element). There are many significant differences between the CSSStyleDeclaration objects that represent inline styles and computed styles:

    Computed style properties are read-only.

    Calculated style properties have absolute values: relative units of measure, such as percentages and points, are converted to absolute values. Any property that specifies size (such as margin width or font size) will have a value expressed in pixels. That is, its value will be a string with the suffix "px", so you will need to parse it, but you won't have to worry about defining and converting units. Property values ​​that define color will be returned in the format "rgb(#,#,#)" or "rgba(#,#,#,#)".

    Properties that are shorthand notation are not evaluated - only the fundamental properties on which they are based. For example, you should not try to get the value of the margin property, but instead access the properties marginLeft, marginTop, etc.

    The cssText property of the computed style is not defined.

Working with computed styles can be quite tricky, and accessing them may not always return the information you expect. Consider the font-family property as an example: it accepts a comma-separated list of font family names for compatibility. When reading the fontFamily property of a computed style, you are waiting for the value of the most specific font-family style applied to the element. And in this case, a value such as “arial, helvetica, sans-serif” may be returned, which does not say anything about the typeface of the actual font used.

Managing Style Sheets

So far we've seen how to set and get CSS style property values ​​and individual element classes. However, there is also the possibility of manipulating the CSS style sheets themselves. This is usually not necessary, but it can sometimes be useful, and this section will briefly outline the possible techniques.

When working with style sheets themselves, you'll encounter two types of objects. The first type is Element objects, which represent elements and that contain or reference style sheets. These are normal document elements, and if you define an id attribute on them, you can select them using the document.getElementById() method.

The second type of object is CSSStyleSheet objects, which represent the style sheets themselves. The document.styleSheets property returns a read-only array-like object containing CSSStyleSheet objects representing the document's style sheets. If you define a title attribute on an or element that defines or references a style sheet, that object will be available as a property of the CSSStyleSheet object with the name specified in the title attribute.

The following sections describe what operations can be performed on these elements and stylesheet objects.

Turning style sheets on or off

The simplest technique for working with style sheets is also the most portable and reliable. Elements and CSSStyleSheet objects define a disabled property that can be read and written by JavaScript scripts. As its name suggests, if the disabled property is set to true, the stylesheet is disabled and will be ignored by the browser.

This is clearly demonstrated by the disableStylesheet() function below. If you give it a number, it will interpret it as an index into the document.styleSheets array. If you pass it a string, it will interpret it as a CSS selector, pass it to the document.querySelectorAll() method, and set the disabled property of all received elements to true:

Function disableStylesheet(ss) ( if (typeof ss === "number") document.styleSheets.disabled = true; else ( var sheets = document.querySelectorAll(ss); for(var i = 0; i

Getting, inserting, and removing rules from style sheets

In addition to providing the ability to enable or disable style sheets, the CSSStyleSheet object also defines an API for retrieving, inserting, and removing style rules from style sheets. IE8 and earlier versions implement a slightly different API than the standard one implemented by other browsers.

In general, directly manipulating style sheets is rarely useful. Rather than adding new rules to style sheets, it is usually better to leave them static and work with the element's className property. However, if you want to give the user full control over your web page's style sheets, you may want to implement dynamic style sheet manipulation.

CSSStyleSheet objects are stored in the document.styleSheets array. The CSSStyle Sheet object has a cssRules property that stores an array of style rules:

Var firstRule = document.styleSheets.cssRules;

In IE this property is called rules, not cssRules.

The elements of the cssRules or rules array are CSSRule objects. In the standard API, a CSSRule object can represent any type of CSS rule, including @rules such as @import and @page directives. However, in IE, the rules array can only contain the actual stylesheet rules.

The CSSRule object has two properties that can be used in a portable way. (In the standard API, non-style rules do not have these properties, so you may need to skip them when traversing the style sheet.) The selectorText property is the CSS selector for the rule, and the style property is a reference to a writable CSSStyleDeclaration object that describes the styles associated with this selector. As a reminder, CSSStyleDeclaration is the same type that is used to represent inline and computed styles.

The CSSStyleDeclaration object can be used to read existing or create new styles in rules. Often, when traversing a style sheet, it is the text of the rule itself that is of interest, not the parsed representation of it. In this case, you can use the cssText property of the CSSStyleDeclaration object, which contains the rules in the text representation.

In addition to the ability to retrieve and modify existing style sheet rules, you have the ability to add rules to and remove rules from the style sheet. The standard application interface defines insertRule() and deleteRule() methods that allow you to add and remove rules:

Document.styleSheets.insertRule("H1 ( text-weight: bold; )", 0);

The IE browser does not support the insertRule() and deleteRule() methods, but it defines addRule() and removeRule() functions that are almost equivalent to them. The only major difference (besides the function names) is that addRule() expects to receive the selector and style as text in two separate arguments.

Creating New Style Sheets

Finally, you can create completely new style sheets and add them to your document. In most browsers, this operation is performed using standard techniques implemented in the DOM: a new element is created and inserted into the document in the section, then the contents of the style sheet are added using the innerHTML property. However, in IE8 and earlier versions, a new CSSStyleSheet object must be created using a non-standard method document.createStyleSheet(), and add style sheet text using the cssText property.

The example below demonstrates the creation of new tables:

// Adds a style sheet to the document and fills it with the specified styles. // The styles argument can be a string or an object. If it is a string, // it is interpreted as stylesheet text. If it is an object, then each // property of it must define a style rule to be added to the table. // The property names are selectors, and their values ​​are the corresponding styles function addStylesheet(styles) ( // First you need to create a new style sheet var styleElt, styleSheet; if (document.createStyleSheet) ( //If the IE API is defined, use it styleSheet = document .createStyleSheet(); ) else ( var head = document.getElementsByTagName("head"); styleElt = document.createElement("style"); // New element head.appendChild(styleElt); // Insert into // Now new the table is at the end of the array styleSheet = document.styleSheets; ) // Insert styles into the table if (typeof styles === "string") ( // Argument contains the text definition of the style sheet if (styleElt) styleElt.innerHTML = styles; else styleSheet .cssText = styles; // IE API ) else ( // Argument object with rules for insertion var i = 0; for(selector in styles) ( if (styleSheet.insertRule) ( var rule = selector + " (" + styles + ")"; styleSheet.insertRule(rule, i++); ) else ( styleSheet.addRule(selector, styles, i++); ) ) ) )

Hello! In this tutorial I would like to talk about how you can change the style of an element on a web page using JavaScript. It must be said that in JavaScript, 2 approaches are usually used to work with styles:

  • Changing the style property
  • Changing an element's class value

style property

The style property represents the so-called inline styles that will be displayed on the element through the style attribute. For example, let's set the font color:

Var root1 = document.documentElement; // set the style root1.style.color = "red"; // get the style value document.write(root1.style.color); //red

In this example, the name of the color property is the same as the same css property. By analogy, you can set the color using css:

Html( color: red; )

However, for those css properties that have a hyphen in the name, for example, font-size. In JavaScript, for these properties, the hyphen is removed, and the first letter after the hyphen is written as a capital letter, that is, in uppercase

Var root1 = document.documentElement; root1.style.fontFamily = "Arial";

className property. Working with classes in JavaScript.

Using a property such as className, you can set the class attribute on any html element. Here's an example:

.redStyle( color:red; font-family:Arial; ) .article( font-size:22px; ) Article title

First paragraph

Another paragraph

var article = document.querySelector("div.art"); // setting a new class article.className = "redStyle"; // get the class name document.write(article.className);

This eliminates the need to configure each individual property using the style property.
However, it should be taken into account that the previous value of the class attribute will be deleted. Therefore, if you need to add a class, then it should be combined with the old class:

Article.className = article.className + "blueStyle";

But if you need to completely remove all classes, you can assign the className property to an empty string:

ArticleDiv.className = "";

The classList property. Adding a new class to an element.

Above we looked at how to add classes to an element on a web page, but to manage a large number of classes it is more convenient to use another property, classList. This property is an object that implements the following methods:

  • add(className): will add a class className
  • remove(className): will remove class className
  • toggle(className): will switch the element's class to className. That is, if there is no class, it will be added, and if there is, it will be removed.

Var article = document.querySelector("div.art"); // remove the class article.classList.remove("art"); // add a class

article.classList.add("redStyle"); // switch class
article.classList.toggle("art");

Results.

To set a class, use the className method.

To set the style of an element through the style attribute, the style method is used.

To add and remove a class to an element, use the classList.add(className) and classList.remove(className) methods.