- Добавляем и удаляем CSS-классы при помощи Javascript
- classList
- JQuery
- Подборка курсов по Javascript
- Комментарии
- 3 Ways JavaScript Add Class
- Add class javascript — 3 ways
- 1. Using classList property
- Adding class javascript on an event
- Add Multiple classes javascript
- 2. Using className property
- Adding multiple classes using className
- 3. Using setAttribute Method
- Adding multiple classes using setAttribute
- JavaScript add class to body
- JavaScript add class to div
- JavaScript add class to new element
- Add a class on hover javascript
- Conclusion
Добавляем и удаляем 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 , и не факт, что он будет хорошо поддерживаться устаревшими браузерами.
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, так как как правило все элементы повторяются на сайте, и только и исключительных случаях они не повторяются.
Кнопки, формы, поля, переключатели, виджеты, почти всегда во множественном количестве присутствуют.
3 Ways JavaScript Add Class
In this article, you will learn 3 different ways JavaScript add class to HTML elements. You will see different variations like adding multiple classes to the element, adding class to the body, creating a new element, etc.
You can either directly add a class to the element as an HTML attribute (Ex:
) or use JavaScript to add a class to the element (which we will see in this section).
Here is an example of adding a class to an HTML element using javascript.
// selecting the element let button = document.querySelector('#button'); // Add class to the element button.addEventListener('click', function() < button.classList.add('.main-btn'); >);
.main-btn < border: none; color: white; background: blue; padding: 10px 30px; border-radius: 5px; >@keyframes shake < 0% < transform: translateX(0) >25% < transform: translateX(-5px) >50% < transform: translateX(0) >75% < transform: translateX(5px) >100% < transform: translateX(0) >> .main-btn:hover
Output : Click the button below and javascript will add a class to the button.
This is a dynamic way of adding a class to an HTML element. Let’s see how javascript adds class dynamically to an HTML element.
Add class javascript — 3 ways
While working on the front end, we often need to add CSS dynamically to an HTML element. To add dynamic CSS to an element add a class to the element.
There are 3 ways to add CSS class using javascript.
1. Using classList property
Every HTML element has a classList property. This property has many different methods. One of the methods is add() method. This method is used to add a class to the element.
element.classList.add('class_name')
To add a CSS class using javascript follow the steps below:
- Select the HTML element.
- Apply the classList property to it.
- Use the add() method to add the class and pass the class name as an argument.
Adding class javascript on an event
In general, we add classes using javascript when an event occurs. For example, when a user clicks on a button, when a user scrolls down the page, etc.
Let’s see how to add a class to an HTML element when a user clicks on a button .
In the above code in the event of a button click a function is executed that adds a class to the paragraph element.
Add Multiple classes javascript
You can also add multiple classes at once using the add() method.
To add multiple classes at once, pass multiple classes separated by a comma.
2. Using className property
The className property of an element can be used to get and set classes attached to the element.
The className property returns the classes of the element in form of a string. If the element has a class named class1 then it returns «class1», if the element has 2 classes class1 and class2 then it returns «class1 class2», and so on.
const element1 = document.getElementById("id1"); const element2 = document.getElementById("id2"); console.log(element1.className); // "box" console.log(element2.className); // "big red box"
The className property can read as well as write the classes of the element.
To add a new class to the element assign the new class to the element’s className property as a string.
Note : Assigning a class name directly to the className property will overwrite the existing classes.
Here is an example to show this.
const element = document.getElementById("id1"); element.className = "box"; // all older classes will be replaced by box
To add new classes without replacing older classes use the += operator to assign the new class. It will keep older classes and adds new ones.
const element = document.getElementById("id1"); element.className += " box"; // must add space before class name // new class added, old one remained
Possible mistake : Add a space before the name of the class when using className to add a class. Because if the element has an old class «class1» and you add the new class «class2» it becomes «class1class2» which is meaningless to the browser.
Adding multiple classes using className
To add multiple classes assign new class names separated by spaces to the className property of the element.
3. Using setAttribute Method
setAttribute is a method that can be used to add a new attribute to an element.
A class is also an element attribute. So we can use the setAttribute method to add a class.
The setAttribute method can be used to add a new attribute to an element. The method takes two parameters, the name of the attribute and the value of the attribute.
// select the button var btn = document.getElementById('btn'); btn.addEventListener('click', function() < // add class btn.setAttribute('class', 'btn'); >);
Adding multiple classes using setAttribute
To add multiple classes to the element pass the multiple class names separated by spaces to the setAttribute method.
// select the button var btn = document.getElementById('btn'); btn.addEventListener('click', function() < // add class btn.setAttribute('class', 'btn danger'); >);
JavaScript add class to body
To add a class to the body of the webpage select the body by document.body and use either of the 2 mentioned methods to add CSS classes.
function addClass()
JavaScript add class to div
As mentioned above you can use any of the above 2 methods to add a class to a div element using javascript.
const div = document.getElementById("id1"); function addClass()
JavaScript add class to new element
Imagine a scenario where you want to add a new element to the webpage like creating a list item in a To Do list app. You can use the classList property to add a class to the new element.
To add multiple classes pass the class names separated by spaces to the classList.add() method.
Add a class on hover javascript
To add a class to an element when mouse hover use onmouseover event. Attach an onmouseover event to the element trigger event handler to add the class.
This is inside a div element const div = document.getElementById("id1"); function addClass()
Conclusion
Summarising the above methods to add a class to an element in JavaScript.
- Method 1 : Use classList.add() Method
- Method 2 : Use className property
- Method 3 : Use setAttribute() method
You can add single or multiple classes to an element using any of the above methods.
If you need assistance with your JavaScript project, feel free to contact experts for getting JavaScript assignment help online.