Contacts

Interaction of JavaScript and CSS. Changing the style of elements How to make applying style through js smooth

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. I must say that in JavaScript, as a rule, 2 approaches are used to work with styles:

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

style property

The style property is 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 style root1.style.color = "red"; // get style value document.write(root1.style.color); // red

In this example, the name of the color property is the same as the corresponding 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 capital, that is, in uppercase

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

className property. Working with classes in JavaScript

With a property like className you can set the class attribute on any html element. Here is 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 class name document.write(article.className);

This eliminates the need to configure each individual property using the style property.
However, keep in mind that the previous value of the class attribute will be removed. 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, then you can assign an empty string to the className property:

ArticleDiv.className = "";

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 classList property. This property is an object that implements the following methods:

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

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

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

Results.

In order to set the class, the method - className is used.

To set a style for an element through the style attribute, use the style method.

ClassList.add(className) and classList.remove(className) methods are used to add and remove a class to an element.

Interaction of JavaScript and CSS

Cascading Style Sheets (CSS) is a visual representation standard for HTML documents. Cascading Style Sheets are designed to be used by designers: they allow you to precisely define fonts, colors, margins, alignment, border settings, and even the coordinates of elements in a document.

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

Managing Inline Styles

The easiest way to control CSS styles is to manipulate the style attribute of individual elements in a document. As with most HTML attributes, the style attribute corresponds to the Element object's property of the same name 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 content of the text element e in large, bold blue, you can perform the following operations to set 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 the CSSStyleDeclaration object, remember that all values ​​must be specified as strings. In a stylesheet 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 language syntax. The semicolons used in CSS style sheets are not needed in string values ​​set with JavaScript.

Also, remember that all positioning properties must specify units of measurement. That is:

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

Units of measure are required when setting style properties in JavaScript, just as they are when setting style properties in stylesheets.

Many CSS style properties, such as font-size, contain hyphens in their names. In JavaScript, the hyphen is interpreted as a minus sign, so the expression below 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 the CSS property name contains hyphens, the property name of the CSSStyleDeclaration object is formed by removing the hyphens and uppercase the letter immediately following each hyphen. In other words, the CSS property border-left-width can be accessed via the borderLeftWidth property, and the CSS property font-family can be accessed via the fontFamily property.

Also, 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 property name for the CSSStyleDeclaration object. That is, to read or change the value of an element's CSS float property, use the cssFloat property of the CSSStyleDeclaration object.

The style attribute of an HTML element is its inline style and it overrides any style rules in the CSS. Inline styles are generally useful for setting style values, and this is the approach used in all of the examples above. Scripts can read the properties of a CSSStyleDeclaration object that represents inline styles, but they only return meaningful values ​​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 string unless that paragraph has a style attribute that overrides the value set by the style sheet.

Reading an element's inline style is especially tricky when you're reading style properties that have units, as well as shorthand properties: the script must include a far from simple implementation of parsing CSS-styled strings to allow values ​​to be retrieved and used later. In general, an inline element style is only useful for setting styles.

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

// Both statements below set the style attribute // of the e element 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 with CSS

One of the most common use cases for CSS is the rendering of 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 positioned 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 the e // element as an argument when the animation finishes playing. The third argument specifies // the offset value of the e element. The default value is 5 pixels. // The fourth argument determines how long the effect should play. // By default, the effect lasts 500ms. function shake(e, oncomplete, distance, time) ( // Handling 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. style.position = "relative"; // Make it relative positioned var start = (new Date()).getTime(); / / Remember when the animation started animate(); // Start the animation // This function checks the elapsed time and changes the coordinates of e. // If it's time to end the animation, restores the initial state of the // element e. Otherwise, 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 start? var fraction = elapsed / time; // Fraction from required time? if (fraction

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

Click me!

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

Computed Styles

The element's style property defines the inline style of the element. It takes precedence over all stylesheets and can be used successfully to set CSS properties to change the visual appearance of an element. However, in general, it makes no sense to refer to it when you want to know the styles actually 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 derived (or computed) from the inline style and all rules from all style sheets that apply to the element: it is the set of properties actually used when the element is rendered. 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 computed style you want to return. The second argument is required and is usually null or an empty string, but it can also be 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 CSSStyleDeclaration objects that represent inline styles and computed styles:

    Computed style properties are read-only.

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

    Shorthand properties 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, instead you should access the marginLeft , marginTop , etc. properties.

    The cssText property of the computed style is not defined.

Computed styles can be tricky to work with, and accessing them doesn't 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. In this case, a value such as "arial,helvetica,sans-serif" might be returned, which says nothing about the typeface of the actual font being used.

Style sheet management

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

When working with style sheets themselves, you will encounter two types of objects. The first type are Element objects that represent and elements that contain or refer to 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 a title attribute is defined 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 style sheet objects.

Turning Style Sheets On and Off

The simplest style sheet technique is also the most portable and reliable. The CSSStyleSheet elements and objects define a disabled property that is available to JavaScript for reading and writing. 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 pass 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 deleting rules from style sheets

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

As a general rule, directly manipulating style sheets is rarely useful. Instead of adding new rules to style sheets, it's usually better to leave them static and work with the element's className property. At the same time, if you want to give the user full control over the style sheets of a web page, you may want to dynamically manipulate the tables.

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 named 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 actual style sheet rules.

The CSSRule object has two properties that can be used in a portable way. (In the standard API, rules that are not style rules do not have these properties, so you may need to skip them when iterating over 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 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, the text of the rule itself 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 text representation.

In addition to the ability to retrieve and modify existing style sheet rules, it is possible to add rules to and remove rules from the style sheet. The standard API defines the insertRule() and deleteRule() methods 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 defines addRule() and removeRule() functions that are almost equivalent to them. The only significant 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, it is possible to create completely new style sheets and add them to the document. In most browsers, this operation is performed using standard DOM tricks: a new element is created and inserted into the document in the section, then the content of the style sheet is added using the innerHTML property. However, in IE8 and earlier, a new CSSStyleSheet object must be created using the 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 style sheet text. If it's an object, then // each of its properties must define a style rule to add 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 an 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 a new the table is at the end of the array styleSheet = document.styleSheets; ) // Insert styles into the table if (typeof styles === "string") ( // The argument contains the textual definition of the stylesheet if (styleElt) styleElt.innerHTML = styles; else styleSheet .cssText = styles; // IE API ) else ( // Argument object with rules to insert var i = 0; for(selector in styles) ( if (styleSheet.insertRule) ( var rule = selector + " (" + styles + ")"; styleSheet.insertRule(rule, i++); ) else ( styleSheet.addRule(selector, styles, i++); ) ) ) )

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

So, those of you who are already at least a little familiar with javascript know that elements have a style property that 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 of the most common 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.

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

In the first case, we will not get anything, but for the div2 block, the styles will be displayed. Why? The thing is that javascript can only display the values ​​of 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 "computed styles". They got their name for a reason. The fact 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 getComputedStyle() function for this. Let's see how it works.

varstyles = 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, then use the code below.

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

Use similar

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

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

Description

The style property represents the global style attribute of an HTML element. The value of the style property is a CSSStyleDeclaration object that contains all of the HTML element's style information, added to the element via the global style attribute. The properties of the CSSStyleDeclaration object are CSS properties.

To change or add new styles to an HTML element, you need to use a property whose name will match the name of the CSS property whose value you want to change. For example, to display the text content of an element in red italics, you can run the following statements:

elem.style.fontStyle = "italic"; elem.style.color = "red";

Note that all property values ​​of the CSSStyleDeclaration object must be specified as strings. For example, in a stylesheet or style attribute, you could write:

Color: red; font-size: 50px; text-decoration: underline;

To do the same in JavaScript, enclose all values ​​in quotes:

elem.style.color = "red"; elem.style.fontSize = "50px"; elem.style.textDecoration = "underline";

Note that semicolons are not included in string values. Semicolons used in CSS are not needed in string values ​​set with JavaScript.

Many CSS properties, such as text-decoration, contain hyphens in their names. In JavaScript, the hyphen is interpreted as a minus operator, so the following statement will not work:

elem.style.text-decoration = "overline";

Thus, the names of the properties of the CSSStyleDeclaration object are slightly different from the names of the actual CSS properties. If the CSS property name contains hyphens, then the property name of the CSSStyleDeclaration object is formed by removing all hyphens and uppercase the letter immediately following each of the hyphens. For example, the list-style-type CSS property in JavaScript would look like listStyleType.

Also, 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 property name. That is, to read or change the value of the float CSS property, use the cssFloat property.

When using the properties of a CSSStyleDeclaration object to read style information about an HTML element, only those properties that have been previously set by a script or set using the style attribute will return meaningful information.

The built-in element style in JavaScript is only useful for setting styles. To get the style information of an element (the value of all CSS properties set for the element), use the window.getComputedStyle() method.

Example Document name

This is a paragraph.

Change text

function foo() ( var x = document.getElementById("test"); var color = " - text color: " + x.style.color; var bold = ".
And now the text is bold."; x.innerHTML += color + bold; x.style.fontWeight = "bold"; )

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 control the classes and styles of elements on the page, respectively.

Managing the class(es) of an element

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 className DOM property was not named class due to the fact that previously in JavaScript, reserved words could not be used as the name of object properties. If you do not 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 perform various operations on the element class using the className DOM property:

varelem = 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 on an element's class is to use methods to manipulate attributes.

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

varelem = 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 className DOM property 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 not one class, but several. In this case, working with them as a string is not very convenient.

For example, determining the presence of a particular class in an element using the above methods can no longer be done so simply. This will require some code to be written.

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

... varelem = document.querySelector("#content"); if ((" " + elem.className + " ").indexOf(" content__show ") > -1) ( // element has class content__show ) else ( // element has no class content__show )

But besides this situation, there are others. For example, when you need to add one specific class to an element, or remove it. To make these actions and others very easy, the element has a special DOM property classList 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 an element. If the element already has this class, then 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 if the element has a class; returns true or false as a response.
  • .toggle(className [,flag]) - toggles the specified class name on the element, i.e. if the element has the given class, removes it; otherwise adds. The second parameter (flag) is optional. It defaults to undefined . If set to true or false , then it will work like an add or remove method, i.e. either add a class to an element or remove it from it.

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

// get element c id = "sidebar" var sideBar = document.querySelector("#sidebar"); // toggle the element's hidden-xs class, i.e. if the element has it, then delete it; and if this class does not exist, then add it to it sideBar.classList.toogle("hidden-xs"); // add three extra classes to the sideBar element. classList. add("col-xs-6","col-sm-4","col-md-3"); // remove the hidden-xs class from the element sideBar. classList.remove("hidden-xs"); // check if the element has a class hidden-lg 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 over as an array.

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

... var content = document.querySelector(".content"); // Option #1. Using the for loop // classList.length - the number of classes in the element // the classes in the 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 that we can use to 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 through the style DOM property:

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

The property names of the style object are usually the same as the names of 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 by capital letters. For example, the background-color CSS property for the style object would be set to backgroundColor . And, for example, a CSS property with the browser prefix -webkit-border-radius - like WebkitBorderRadius .

Removing Styles

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

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

If now this style needs to be removed, then in order to do this, we must simply assign an empty string to it:

Document.body.style.backgroundColor = "";

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

// set element with id = "introtext" using style to red text color document.querySelector("#introtext").style.color = "red"; // set all p elements on the page using style to green text color 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 all at once using the style.cssText special property. This is done by assigning to 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 where we set styles "font-size:40px; color:blue;" elements with class intro:

//get elements with class intro var intro = document.querySelectorAll("intro"); //set "font-size:40px; color:blue;" to 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 with the style.cssText property. This is because, when set, this property removes all styles that the element has. Those. the ones we set to it with the style attribute and in its corresponding DOM property.

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

For example:

//get the first element with class intro var info = document.querySelector("info"); //set its style to "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 class text: 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 style "width: 180px; height: 180px;" all elements on the page with a class that starts with the words block- .



Liked the article? Share it