How to Check if element has class in JavaScript

Проверяем наличие класса у элемента на jQuery/JavaScript

В этой статье я хотел бы показать вам несколько способов, способных организовать проверку на наличие класса в неком элементе. Самих по себе классов, как вы знаете, у элемента может быть несколько, и все они указываются через пробел.

Наша же задача – проверить, присутствует ли определенный класс (или несколько классов) у элемента или нет, и дальше выполнить нужное нам действие.

Все описанные способы мы будем тестировать на конструкции:

А теперь о каждом подробнее.

Проверяем наличие класса у элемента на jQuery

В jQuery проверка наличия класса осуществляется посредством метода hasClass.

   

Для отрицания (то есть для проверки отсутствия класса) вы добавляете знак восклицания:

   

В таком случае действие будет выполнено, если указанный класс отсутствует.

Проверяем наличие класса у элемента на JavaScript

В JavaScript код будет чуть больше, но по конструкции аналогичен варианту с jQuery:

   

Здесь мы делаем проверку на наличие, а здесь:

   

соответственно, на отсутствие.

Мелочи, но весьма нужные инструменты в арсенале разработчика.

Источник

How to Check if element has class in JavaScript

CSS classes are very helpful when need to add same style on multiple HTML elements.

Sometimes need to perform an action based on a class element has.

In this tutorial, I show how you can check if element has a specific class using JavaScript with examples.

How to Check if element has class in JavaScript

Contents

1. Check class on a single element using JavaScript

  • Create a and added class red to it.
  • Create a button that calls hasClass() function. Pass instance and class name that needs to check.
  • In example, I am checking red class on .
  • Display class status in using JavaScript.
  • Create hasClass() function.
  • It takes 2 parameters –
    • Element instance in which search class.
    • Class name that needs to find.
            .content < width: 100px; height: 100px; color: white; >.red 

    Search class on single element





    Result :

    2. Check class on multiple elements using JavaScript

    Created 3 elements. 2 has red class and 1 has blue class. 1 button to search red class.

    Display ids that has red class in .

    This function calls on button click. This function takes 1 parameter – search class name. Loop on that has class name content. Pass instance and classname variable in hasClass() function.

    If it returns true then read id attribute and append in ids variable.

    Completed Code

            .content < width: 100px; height: 100px; display: inline-block; color: white; >.red < background: red; >.blue 

    Search class on multiple elements



    Result

    // Search class function hasClass(el,classname)< if(el.classList.contains(classname))< return true; >else < return false; >> // Multiple search function checkClass(classname) < var div = document.getElementsByClassName('content'); var totalel = div.length; var ids = ""; for(var i=0;idocument.getElementById('result2').innerHTML = ids; > >

    3. Conclusion

    I hope using the examples you have successfully implemented class searching using JavaScript.

    You can view this tutorial to know class searching using jQuery.

    If you found this tutorial helpful then don’t forget to share.

    Источник

    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

    classList.contains("class-name") 

    Here’s an example. Say you’ve got the following HTML:

    div id="box1" class="active">div>
    div id="box2">div>

    Then you can check if these boxes have the class active using the following JavaScript:

    const box1 = document.querySelector('#box1');
    const box2 = document.querySelector('#box2');

    box1.classList.contains('active'); // true
    box2.classList.contains('active'); // false

    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 . ).

    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:

    const element = document.querySelector("#my-element");

    Make sure to update the selector based on your HTML code.

    You can add a class to an element with classList.add:

    element.classList.add("some-class");

    Also, adding more than 1 class is possible. You can pass every class you want to add as an extra argument:

    element.classList.add("some-class", "another-class");

    After running this line, the element would look like this:

    div id="my-element" class="some-class another-class">div>

    You can also remove one more classes.
    Let’s start by removing the class active

    element.classList.remove("active");

    Similarly to classList.add, you can also remove multiple classes at the same time by passing the class names as different arguments:

    element.classList.remove("first-class", "another-class");

    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).

    element.classList.toggle("some-class", "another-class");

    Here’s an example of how you can toggle an element to become active:

    element.addEventListener("click", event => 
    event.currentTarget.classList.toggle("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.

    This is a useful «shortcut» as it allows you to replace 2 lines with 1.

    You can replace the following 2 lines:

    element.classList.remove("old-one");
    element.classList.add("new-one");
    element.classList.replace("old-one", "new-one");

    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:

    Learn JavaScript Blog

    Learn JavaScript Blog | Learn about the latest JavaScript news

    Источник

    Check If an Element contains a Class

    To check if an element contains a class, you use the contains() method of the classList property of the element:

    element.classList.contains(className);Code language: CSS (css)

    In this method, you pass the className to the contains() method of the classList property of the element. If the element contains the className , the method returns true . Otherwise, it returns false .

    For example, suppose you have the following element with two classes: secondary and info :

    div class="secondary info">Item div>Code language: HTML, XML (xml)

    To check if the element contains the secondary class, you use the following code:

    const div = document.querySelector('div'); div.classList.contains('secondary'); // trueCode language: JavaScript (javascript)

    In this example, we use the querySelector() method to select the div and use the contains() method to check if its class list contains the secondary class.

    The following example returns false because the element doesn’t have the error class:

    const div = document.querySelector('div'); div.classList.contains('error'); // falseCode language: JavaScript (javascript)

    Summary

    Источник

    Javascript check if element has class

    Last updated: Jan 11, 2023
    Reading time · 2 min

    banner

    # Check if an Element does NOT have a specific Class using JS

    Use the classList.contains() method to check if an element does not have a specific class.

    If the element does not have the provided class, the method returns false , otherwise true is returned.

    Here is the HTML for the example.

    Copied!
    DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> style> .bg-salmon background-color: salmon; > style> head> body> div id="box" class="bg-salmon">Box 1div> script src="index.js"> script> body> html>

    And here is the related JavaScript code.

    Copied!
    const box = document.getElementById('box'); if (!box.classList.contains('bg-salmon')) console.log('Element does NOT have class'); > else console.log('Element has class'); >

    We used the classList.contains method to check if the element does not have a class name.

    The contains() method returns true if the element has the provided class and false otherwise.

    Copied!
    const box = document.getElementById('box'); // 👇️ true console.log(box.classList.contains('bg-salmon')); // 👇️ false console.log(box.classList.contains('does-not-exist'));

    We used the logical NOT (!) operator to negate the result returned from the contains() method.

    When used with boolean values, like in the example, the operator flips the value, e.g. true becomes false and vice versa.

    Copied!
    console.log(!true); // 👉️ false console.log(!false); // 👉️ true

    If the element doesn’t contain the bg-salmon class, our if block runs, otherwise, the else block runs.

    Copied!
    const box = document.getElementById('box'); if (!box.classList.contains('bg-salmon')) console.log('Element does NOT have class'); > else console.log('Element has class'); >

    Note that if you are checking if a certain class is not present because you don’t want to add it twice, you can use the classList.add() method to avoid this scenario.

    Copied!
    const box = document.getElementById('box'); // ✅ Add classes to element box.classList.add('first-class', 'second-class'); // ✅ Remove classes from element box.classList.remove('third-class', 'fourth-class');

    The classList.add() method adds one or more classes to an element. If any of the provided classes already exists on the element, the class is omitted.

    The classList.remove() method removes one or more classes from the element. If the class does not exist on the element, the method ignores the class and does not throw an error.

    I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

    Источник

    Читайте также:  Метод add python class
Оцените статью