Javascript remove class and add class to

Добавляем и удаляем CSS-классы при помощи Javascript

В этой статье мы расскажем о двух способах манипуляции с HTML class . В первом используется Javascript-свойство classList , а во втором задействуется библиотека jQuery . Для начала, взгляните на следующий код:

В нем представлена кнопка с событием onclick , которое позволяет переключать цвет кнопки. CSS-код определяет классы для установки цвета фона:

Единственное, что здесь остается сделать, это реализовать функцию toggleColor() :

classList

У каждого элемента есть свойство classList , которое содержит в себе атрибуты HTML style class . Это свойство включает в себя методы, позволяющие добавлять или удалять классы:

function toggleColor() < var myButtonClasses = document.getElementById("btn1").classList; if (myButtonClasses.contains("blue")) < myButtonClasses.remove("blue"); >else < myButtonClasses.add("blue"); >if (myButtonClasses.contains("red")) < myButtonClasses.remove("red"); >else < myButtonClasses.add("red"); >>

В приведенном выше примере используется три метода classList .

  • contains() – возвращает значение true , если у элемента имеется родительский класс. Если же его нет, то возвращается значение false ;
  • add() – добавляет заданный класс к элементу. Это действие игнорируется, если элемент уже содержит заданный класс;
  • Remove() — заданный класс, при его наличии, удаляется.

Эту задачу можно решить проще при помощи метода toggle() , который добавляет указанный атрибут class в HTML при его отсутствии, или удаляет его, если он уже применен:

При работе с несколькими классами их можно разделять запятыми:

document.getElementById("btn1").classList.toggle("blue”, “bold"); document.getElementById("btn1").classList.toggle("red”, “italics");

Единственный недостаток данного подхода заключается в том, что он был представлен лишь в HTML5 , и не факт, что он будет хорошо поддерживаться устаревшими браузерами.

Читайте также:  Graph program in python

JQuery

jQuery предлагает методы, которые работают по тому же принципу. Но также позволяют использовать укороченные свойства для выделения элементов. Давайте посмотрим, как функция toggleColor() должна быть написана на jQuery :

Можно использовать addClass() , removeClass() и hasClass() для toggleColor() . Обратите внимание, что новые HTML style class можно перечислять через пробел в той же строке.

$("#btn1").toggleClass("blue bold"); $("#btn1").toggleClass("red italics");

На этом все! Теперь вы знаете, как без труда изменять внешний вид DOM-элементов !

Подборка курсов по Javascript

4.4 GeekBrains еще 4 курса

4.4 Нетология еще 3 курса

4.4 Яндекс.Практикум еще 2 курса

4.2 Оtus

4.4 Skillbox

4.5 LoftSchool

Комментарии

писец.
1.Почему не выделили в список методы для управления классами?
И почему в списке нет метода Toggle, но при этом его внизу описывают как будто это бесполезный метод и в список его заносить не нужно.
2.А что для работы с элементами люди пользуются ID только?, я вот искал как JS по классу находит элемент и добавляет, удаляет другие классы. Люди стараются наоборот не использовать ID, так как как правило все элементы повторяются на сайте, и только и исключительных случаях они не повторяются.
Кнопки, формы, поля, переключатели, виджеты, почти всегда во множественном количестве присутствуют.

Источник

Element: classList property

The Element.classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element. This can then be used to manipulate the class list.

Using classList is a convenient alternative to accessing an element’s list of classes as a space-delimited string via element.className .

Value

A DOMTokenList representing the contents of the element’s class attribute. If the class attribute is not set or empty, it returns an empty DOMTokenList , i.e. a DOMTokenList with the length property equal to 0 .

Although the classList property itself is read-only, you can modify its associated DOMTokenList using the add() , remove() , replace() , and toggle() methods.

You can test whether the element contains a given class using the classList.contains() method.

Examples

const div = document.createElement("div"); div.className = "foo"; // our starting state: console.log(div.outerHTML); // use the classList API to remove and add classes div.classList.remove("foo"); div.classList.add("anotherclass"); // console.log(div.outerHTML); // if visible is set remove it, otherwise add it div.classList.toggle("visible"); // add/remove visible, depending on test conditional, i less than 10 div.classList.toggle("visible", i  10); // false console.log(div.classList.contains("foo")); // add or remove multiple classes div.classList.add("foo", "bar", "baz"); div.classList.remove("foo", "bar", "baz"); // add or remove multiple classes using spread syntax const cls = ["foo", "bar"]; div.classList.add(. cls); div.classList.remove(. cls); // replace class "foo" with class "bar" div.classList.replace("foo", "bar"); 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • element.className
  • DOMTokenList
  • classList.js (a cross-browser JavaScript polyfill that fully implements element.classList )

Found a content problem with this page?

This page was last modified on May 26, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How to add, remove, and toggle CSS classes in JavaScript

As a web developer, you are often required to add, remove, and toggle CSS classes based on user interactions with elements on the web page. If you had already used jQuery in the past, you’d be probably familiar with the addClass() , removeClass() , and toggleClass() methods.

In modern JavaScript, it makes no sense to load the complete jQuery library to do some simple DOM manipulations. In this article, you’ll learn how to add, remove, and toggle CSS classes in JavaScript without jQuery.

The simplest way to get and set CSS classes in JavaScript is using the className property. It refers to the value of the HTML element’s class attribute. Let us say we have the following HTML element:

The following example shows how to add a new CSS class or replace all existing CSS classes of the above

element:
const pizza = document.querySelector('.pizza') // print existing classes console.log(pizza.className) // pizza // add new `.spicy` class pizza.className += 'spicy' // replace all existing classes pizza.className = 'hot spicy pizza' 

Since class is a reserved word in JavaScript, the name className is used for this property. This property is supported by all modern and old browsers, including Internet Explorer.

There is even a better way to manipulate CSS classes in JavaScript, thanks to the classList property. It is a read-only property that returns a live DOMTokenList collection of all the classes applied to the element. The classList property works in all modern browsers and IE10 and above. You can use the classList property to easily add, remove, and toggle CSS classes from an element in vanilla JavaScript. Say we have an element like the below:

div class="hot spicy pizza"> 🍕 div> 
// grab element reference const pizza = document.querySelector('.pizza') // get all existing classes console.log(pizza.classList) // ["hot", "spicy", "pizza", value: "hot spicy pizza"] // get first class name console.log(pizza.classList[0]) // hot // get total number of classes console.log(pizza.classList.length) // 3 

Let us now look at the popular methods of the DOMTokenList collection, returned by the classList property. We’ll use these methods to manage and update CSS classes for an HTML element.

The item() method returns the class in the collection by its index, or undefined if the index is greater than or equal to the list’s length property:

console.log(pizza.classList.item(1)) // spicy 
pizza.classList.add('sauce', 'cheese', 'tomato') 
div class="hot spicy pizza sauce cheese tomato"> 🍕 div> 

If you try to add a class that already exists, the add() method will ignore it. To see how it works, let us add more cheese to the pizza:

div class="hot spicy pizza cheese tomato"> 🍕 div> 
console.log(pizza.classList.contains('cheese')) // true console.log(pizza.classList.contains('yogurt')) // false 
pizza.classList.remove('sauce', 'potato') 

If you try to remove a class that doesn’t exist, as we did in the above example, there won’t be any error. JavaScript will completely ignore it.

The toggle() method removes the class if it already exists. Otherwise, it adds to the collection. Without this method, you have to manually check if the class exists using contain() before toggling it on or off:

// manual toggle if (pizza.classList.contains('olive'))  pizza.classList.remove('olive') > else  pizza.classList.add('olive') > 
pizza.classList.toggle('olive') 
const status = pizza.classList.toggle('olive') console.log(status) // true --> class was added 

You can also pass a second boolean parameter to the toggle() method to indicate whether to add the class or remove it. This will turn toggle() into one way-only operation. If the second argument evaluates to false , then the class will only be removed but not added. If it evaluates to true , then the class will only be added but not removed. Here is an example:

const status = pizza.classList.toggle('hot', false) console.log(status) // false --> class was removed 
pizza.classList.replace('spicy', 'olive') 

This method returns true if the target class is successfully replaced with the new class. Otherwise, false .

The replace() method is not supported by Internet Explorer. You can use remove() along with add() to replace a CSS class in older browsers.

// iterate over all classes pizza.classList.forEach((item, index) =>  console.log(item) >) 

That’s all! In this article, we looked at two properties ( className & classList ) to manipulate CSS classes in JavaScript. The className property presents the class attribute of the element and is supported by all browsers, including Internet Explorer. It can be used to add a new class or replace an existing class. On the other hand, the classList property returns a live DOMTokenList collection of all the classes applied to a DOM element. It can easily add, remove, toggle, and iterate through all CSS classes. Read Next: Hide and show DOM elements using a CSS class in JavaScript ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

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