Changing the style of elements. JavaScript examples open

Changing the style of elements. JavaScript examples

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators

Changing the style of elements in JavaScript can be done in two ways by changing linear class styles or adding/removing element classes.

Style

style – contains a set of CSS properties: element.style.cssProperty

    var links = document.querySelectorAll('a');
    links.style.color = "red";//set the style color:red;

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

    a{
    color:red;
    }

If a property in CSS has a hyphen, for example font-family. Then this property should be converted to camelCase style:

    links.style.fontFamily = "Verdana";

className

Using the className property, you can set the class attribute of an HTML element:

    var link = document.querySelector("a");//select the link
    link.className = "blue";//add a new class "blue" to the element classes

Our link will change to Home

Already in the CSS file, you can write new properties for this link:

.blue {
        color: blue;
    }
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:
     link.className + "blue";
If you want to remove all classes, then you can set the properties to an empty string:
    link.className = "";

classList

To manage many classes, it is much more convenient to use the classList property

    link.classList.add('blue');//adds a class without removing others
    link.classList.remove('blue');//deletes the class
    link.classList.toggle('blue');// if the class does not exist, then it is added; if there is, then it is removed
0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation