Changing the style of elements. Dynamic Styling - Controlling CSS with JavaScript Changing javascript styles

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

Let's take a (for the moment) theoretical example - let's say we have a website with a series of technical articles. We want to draw attention to some of these articles with a fun animated carousel, but what about users who don't have JavaScript enabled for some reason? Remembering what we learned about unobtrusive JavaScript, we want the features of the Web site to also work for these users, but we may want to style the site differently for these users so that they can use the site comfortably, even without the 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 to be deleted.

In the article demo example, you can create a rule that sets the display property to none for all HTML and JavaScript articles - see 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 the rules according to the standards. Instead of the cssRules attribute, it uses rules . IE also uses removeRule instead of deleteRule and addRule( selector , rule, index) instead of insertRule .

Changing element styles

Now you should understand how to edit the style sheets linked to the page and create and modify CSS rules in them. What if you want to change a certain element in the DOM ? Using the DOM API, you can access certain elements of the page. Going back 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 body of the article is displayed below.

Through the DOM, we access the style object, which describes the style of the document. This style object is defined as a 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 works differently than some of the other properties defined on the HTML element. Unlike element.href or element.id , which return strings, element.style returns a . This means that it is not possible to set the style by assigning a string to element.style .

The style object has attributes that correspond to the various set CSS properties. For example, style.color returns the color set on the element. By doing element.style.color = "red"; you can dynamically change the style. Below is a function that turns the color of an element to red when given 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"); on the element. , but be careful, as this will remove any changes made to the style object.

When an element's style is set in this way, it is the same as if we set it as a declaration of the style attribute of the 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

Last update: 1.11.2015

There are two main approaches to working with element style properties in JavaScript:

    Changing the style property

    Changing the value of the class attribute

style property

The style property represents a complex object for style management and maps directly to the style attribute of an html element. This object contains a set of CSS properties: element.style.CSS property. For example, set the font color:

var root = document.documentElement; // set style root.style.color = "blue"; // get the style value document.write(root.style.color); // blue

In this case, the name of the color property is the same as the css property. Similarly, we could set the color with css:

Html(color:blue; )

However, a number of css properties have a hyphen in their names, such as font-family . JavaScript does not use hyphens for these properties. Only the first letter after the hyphen is converted to upper case:

var root = document.documentElement; root.style.fontFamily = "Verdana";

classname property

The className property can be used to set the class attribute of an html element. For example:

.blueStyle( color:blue; font-family:Verdana; ) .article( font-size:20px; ) Article title

First paragraph

Second paragraph

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

By using classes, you don't have to set every single css property with the style property.

However, it should be taken into account that the previous value of the class attribute is removed. Therefore, if we need to add a class, we need to combine its name with the old class:

ArticleDiv.className = articleDiv.className + "blueStyle";

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

ArticleDiv.className = "";

classList property

We've seen how to add classes to an element above, but it's much more convenient to manage multiple classes using the classList property. This property represents an object that implements the following methods:

    add(className) : adds the class className

    remove(className) : Removes the class className

    toggle(className) : Toggles an element's class to className. If the class does not exist, then it is added, if it exists, then it is removed.

For example:

Var articleDiv = document.querySelector("div.article"); // remove class articleDiv.classList.remove("article"); // add class articleDiv.classList.add("blueStyle"); // toggle class articleDiv. classList. toggle("article");

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

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, 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 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.

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 we 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.