How to check class is available or not in javascript?


Check if the class exists on-page in jquery?

If you want to check your class on the page available or not then you need to use very simple hasClass() method of the jquery and also you can check with using plain javascript. Both example given below:

Has class in jquery:
 <style>
        .test { color#0f0; }
        .searchClassName { color#f00; }
 </style>

<div class="mainBox">MainBox content</div>

    <div class="searchClassName">This is has class</div>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {

            var hassClass = $("div").hasClass("searchClassName");

            if (hassClass == true) {
                $('.mainBox').addClass('test');
            } else {
                $('.mainBox').removeClass('test');
            }

        });
    </script>

Has class in the Javascript :
<div id="mainBox" class="myClass">Has class in javascript</div>
    <div id="myContainer"> We add new class in this section</div>
    <script>
        var checkBoxxClass = document.querySelector("#mainBox");
        var checkClass = checkBoxxClass.classList.contains("myClass");

        var elmName = document.getElementById("myContainer");
        if (checkClass) {
            elmName.classList.add("myNewClassAddName");
        }
    </script>


You will find the result as a given screenshot:


No comments:

Note: Only a member of this blog may post a comment.

Copyright Reserved to Anything Learn. Powered by Blogger.