Element.classList
Свойство classList возвращает псевдомассив DOMTokenList , содержащий все классы элемента.
Примечание: У classList есть примитивная альтернатива — свойство className, которое содержит значение атрибута class элемента.
Синтаксис
- Результат — псевдомассив DOMTokenList , содержащий все классы узла elem
Методы
ClassList является геттером. Возвращаемый им объект имеет несколько методов:
add( String [,String] )
Добавляет элементу указанные классы
remove( String [,String] )
**Удаляет у элемента указанные классы item ( Number ) Результат аналогичен вызову сlassList[Number] toggle ( String [, Boolean]) Если класс у элемента отсутствует — добавляет, иначе — убирает. Когда вторым параметром передано false — удаляет указанный класс, а если true — добавляет. Если вторым параметром передан undefined или переменная с typeof == ‘undefined’, поведение будет аналогичным передаче только первого параметра при вызове toggle. contains ( String ) Проверяет, есть ли данный класс у элемента (вернёт true или false)
Примечание: И, конечно же, у ClassList есть заветное свойство length, которое возвращает количество классов у элемента.
JavaScript hasclass using classList
If you’re looking for JavaScript has class or JavaScript hasclass then there’s a high probability that you used to work with jQuery in the past.
It’s great news that you don’t need a library anymore to check if an element has a class or not because you can now simply do it with a call to
Here’s an example. Say you’ve got the following HTML:
Then you can check if these boxes have the class active using the following JavaScript:
Function signature permalink
The function signature is:
Note that you should only give the className rather than a selector with a «.» because classList is only expecting a class name rather than a selector.
For example, document.querySelector(«#box1»).classList.contains(«.active») is incorrect ❌. It’s looking for a class name of .active . Instead, it should be active (without the . ).
What is classList? permalink
Any DOM element will have a classList object which contains a collection of methods that let you manage the classes, such as adding/removing.
Here are some of the most common use cases you can do with classList:
The examples below assume the following HTML:
which then we select using querySelector:
Make sure to update the selector based on your HTML code.
Add one or more classes permalink
You can add a class to an element with classList.add:
Also, adding more than 1 class is possible. You can pass every class you want to add as an extra argument:
After running this line, the element would look like this:
Remove one or more classes permalink
You can also remove one more classes.
Let’s start by removing the class active
Similarly to classList.add, you can also remove multiple classes at the same time by passing the class names as different arguments:
Toggle classes permalink
Toggling classes is especially useful when you have a click event handler and what to add a class the first time, then remove it the next it’s clicked (and so on).
Here’s an example of how you can toggle an element to become active:
This will end up adding the class active the first time you click on element and then remove it the next time you click on it.
Replace class permalink
This is a useful «shortcut» as it allows you to replace 2 lines with 1.
You can replace the following 2 lines:
By just one clean line:
Do you want to Learn JavaScript step by step?
Checkout my interactive course where you read short lessons, solve challenges in the browser and recap topics with Flashcards:
.hasClass()
Description: Determine whether any of the matched elements are assigned the given class.
version added: 1.2 .hasClass( className )
Elements may have more than one class assigned to them. In HTML, this is represented by separating the class names with a space:
The .hasClass() method will return true if the class is assigned to an element, even if other classes also are. For example, given the HTML above, the following will return true :
While this would return false :
As of jQuery 1.12/2.2, this method supports XML documents, including SVG.
Example:
Looks for the paragraph that contains 'selected' as a class.
Books
Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath
Проверяем наличие класса у элемента на jQuery/JavaScript
В этой статье я хотел бы показать вам несколько способов, способных организовать проверку на наличие класса в неком элементе. Самих по себе классов, как вы знаете, у элемента может быть несколько, и все они указываются через пробел.
Наша же задача – проверить, присутствует ли определенный класс (или несколько классов) у элемента или нет, и дальше выполнить нужное нам действие.
Все описанные способы мы будем тестировать на конструкции:
А теперь о каждом подробнее.
Проверяем наличие класса у элемента на jQuery
В jQuery проверка наличия класса осуществляется посредством метода hasClass.
Для отрицания (то есть для проверки отсутствия класса) вы добавляете знак восклицания:
В таком случае действие будет выполнено, если указанный класс отсутствует.
Проверяем наличие класса у элемента на JavaScript
В JavaScript код будет чуть больше, но по конструкции аналогичен варианту с jQuery: