Javascript изменение css класса

How can I change an element’s class with JavaScript?

How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?

«The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class.» -w3schools.com/tags/att_standard_class.asp

element.setAttribute(name, value); Replace name with class . Replace value with whatever name you have given the class, enclosed in quotes. This avoids needing to delete the current class and adding a different one. This jsFiddle example shows full working code.

For changing a class of HTML element with onClick use this code: and in javascript section: function addNewClass(elem) < elem.className="newClass"; >Online

@Triynko — that link on w3schools has changed, looks like in September 2012. Here is that page on Archive.org from 12/Sep/2012: HTML class Attribute-w3schools. Here is the link for the replacement page on w3schools.com: HTML class Attribute-w3schools.

Читайте также:  Python csv reader last row

34 Answers 34

Modern HTML5 Techniques for changing classes

Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

document.getElementById("MyElement").classList.add('MyClass'); document.getElementById("MyElement").classList.remove('MyClass'); if ( document.getElementById("MyElement").classList.contains('MyClass') ) document.getElementById("MyElement").classList.toggle('MyClass'); 

Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.

Simple cross-browser solution

The standard JavaScript way to select an element is using document.getElementById(«Id») , which is what the following examples use — you can of course obtain elements in other ways, and in the right situation may simply use this instead — however, going into detail on this is beyond the scope of the answer.

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass"; 

(You can use a space-delimited list to apply multiple classes.)

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

document.getElementById("MyElement").className += " MyClass"; 

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace ( /(?:^|\s)MyClass(?!\S)/g , '' ) /* Code wrapped for readability - above is all one statement */ 

An explanation of this regex is as follows:

(?:^|\s) # Match the start of the string or any single whitespace character MyClass # The literal text for the classname to remove (?!\S) # Negative lookahead to verify the above is the whole classname # Ensures there is no non-space character following # (i.e. must be the end of the string or space) 

The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

To check if a class is already applied to an element:

The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) ) 

Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onClick=»this.className+=’ MyClass'» ) this is not recommended behavior. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.

The first step to achieving this is by creating a function, and calling the function in the onClick attribute, for example:

  .  

(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)

The second step is to move the onClick event out of the HTML and into JavaScript, for example using addEventListener

 function changeClass() < // Code examples from above >window.onload = function() . 

(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading — without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)

JavaScript Frameworks and Libraries

The above code is all in standard JavaScript, however, it is common practice to use either a framework or a library to simplify common tasks, as well as benefit from fixed bugs and edge cases that you might not think of when writing your code.

Whilst some people consider it overkill to add a ~50 KB framework for simply changing a class, if you are doing any substantial amount of JavaScript work or anything that might have unusual cross-browser behavior, it is well worth considering.

(Very roughly, a library is a set of tools designed for a specific task, whilst a framework generally contains multiple libraries and performs a complete set of duties.)

The examples above have been reproduced below using jQuery, probably the most commonly used JavaScript library (though there are others worth investigating too).

(Note that $ here is the jQuery object.)

Changing Classes with jQuery:

$('#MyElement').addClass('MyClass'); $('#MyElement').removeClass('MyClass'); if ( $('#MyElement').hasClass('MyClass') ) 

In addition, jQuery provides a shortcut for adding a class if it doesn’t apply, or removing a class that does:

$('#MyElement').toggleClass('MyClass'); 
$('#MyElement').click(changeClass); 
$(':button:contains(My Button)').click(changeClass); 

Источник

Как изменить свойство класса css через js

Для изменения уже определенного значения одного из свойств css-класса элемента, можно воспользоваться следующим примером:

 --Добавим стилей для элемента которые будем менять--> .box  width: 75px; height: 75px; background-color: #444; >   class="box">
onClick="changeColor();">Change color onClick="addWidth();">Add width

в секции со скриптами HTML документа, надо добавить определение указанных функций на кнопках со следующей логикой:

cоnst chаngeColor = () =>  // Выбираем элемент на странице, получаем доступ к списку стилей и меняем нужному значение. documеnt.getElementsByClassName('box')[0].stylе.backgroundColor = "#38d9a9"; > cоnst аddWidth = () =>  documеnt.getElementsByClassName('box')[0].stylе.width = "175px"; > 

Источник

Изменение CSS классов через JavaScript

Изменение CSS классов через JavaScript

На предыдущем уроке мы разобрали, как можно менять отдельные CSS свойства у элементов при помощи JavaScript. Однако будет ли такое действие эффективным, если понадобится изменить сразу много свойств у объекта. И как следствие, придется написать много строк JavaScript кода.

К счастью есть другой способ, как одновременно присвоить много свойств элементу — это прописать ему название класса. Надо просто создать в CSS новый класс, прописать в нем все необходимые стили и затем динамически добавлять новые классы к объектам через JavaScript. Давайте заменим в этом параграфе цвет, толщину и шрифт у текста.

Изменение CSS классов через JavaScript.

//HTML разметка

Мудрая цитата

Самая важная вещь — уметь наслаждаться жизнью
и быть счастливым. Это все, что имеет значение.

//CSS стили
.container width: 400px;
border: 8px solid plum;
margin: 20px auto;
>

#header font-size: 24px;
font-weight: 700;
color: purple;
font-family: ‘Arial Narrow Bold’, sans-serif;
text-align: center;
>

.text font-size: 18px;
font-weight: 200;
font-family: sans-serif;
text-align: center;
padding: 10px;
>

Изменение класса

Все перечисленные свойства для замены находятся в классе text. Создадим новый класс supertext, но с другими значениями.

.supertext font-size: 16px;
font-weight: 700;
font-family: Tahoma;
color:royalblue;
text-align: center;
padding: 10px;
>

Затем, чтобы присвоить параграфу новый класс, мы должны найти объект с классом text и через свойство className присвоить ему новый класс.

//JavaScript
let headerElement = document.querySelector(‘.text’);
headerElement.className = «supertext»;

Теперь в HTML разметке у тега p появился новый класс supertext, вместо старого. И мы видим, как изменился внешний вид текста.

Изменение CSS классов через JavaScript.

Добавление класса

Как быть, если мы хотим не заменять класс, а добавить новый класс к существующему. В этом случае, надо использовать оператор сложения с присваиванием (+=). Мы создали новый класс underline с одним единственным свойством подчеркивания.

.underline text-decoration: underline;
>

В цикле for JavaScript пройдется по всем тегам span с классом green и добавит к ним класс underline (с пробелом спереди). Так мы сохраним акцентные слова зелеными и добавим им подчеркивание. Обратите внимание, что для поиска нескольких элементов, мы использовали метод querySelectorAll.

let greenElement = document.querySelectorAll(‘.green’);
for (let i = 0; i < greenElement.length; i++) greenElement[i].className += " underline";
>

В HTML разметке произошли динамические изменения: теперь у тега span, есть два класса. Если бы мы не оставили перед underline пробел, то оба класса слились бы в одно слово. Тогда мы получили бы совсем другой результат.

Изменение CSS классов через JavaScript.

Альтернативный способ добавления класса

Есть еще один способ добавить класс, через свойство classList.

Создано 07.04.2021 10:43:39

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Как изменить свойство класса с помощью js?

    Есть div с классом mystyle . В классе есть свойство margin как его изменить с помощью обычного js или jquery?

    4 ответа 4

    document.getElementsByClassName('mystyle')[0].style.margin = "50px"; 
    document.getElementsByClassName('mystyle')[0].style= "margin: 50px"; 

    Если нужно поменять во всех элементах этого класса:

    Если прямо в стилях нужно поменять:

    $(function() < var ss = document.styleSheets[0]; var rules = ss.cssRules || ss.rules; var h1Rule = null; for (var i = 0; i < rules.length; i++) < var rule = rules[i]; if (/(^|,) *\.mystyle *(,|$)/i.test(rule.selectorText)) < h1Rule = rule; break; >> h1Rule.style.margin='10px' console.log(h1Rule.style.margin) >);
    function getClassByName(className)

    Невозможно переписывать CSS стиле с помощью JS. Лучше создай новый класс с нужными свойствами и добавляй его.

     .mystyle, .mystyle ul < margin: 0; >.mystyle.active < margin: 20px 0; >.mystyle.active ul
     document.querySelector('.mystyle').classList.add('active'); 

    Связанные

    Похожие

    Подписаться на ленту

    Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

    Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.7.24.43543

    Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

    Источник

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