Javascript check if class exist

Check If Class Exists JavaScript

In this tutorial we will learn how to Check If HTML Element of particular Class Exists using JavaScript. HTML DOM getElementsByClassName() method and .length property can be used for this purpose.

HTML Code

HTML Code is given below, in this code we have a paragraph tag with class red, we also have a button tag with onclick event.

My Class is Red

JavaScript Code

Take a look at the JavaScript code, the HTML Dom getElementsByClassName() method is used with .length property.

HTML Dom getElementsByClassName() is used to select all HTML elements with particular class.

.length property returns the length of a string. In this example it is used to count the number of selected elements with defined class (red).

If answer of elements.length is greater than 0, it means the class exist.

  

Another way to check this is by using the following code.

In above code .classList property is used which is used to return the class names as object.

.contains is used to check the class in the classList object. The answer of .contains is a Boolean value.

Demo

Video Tutorial

Источник

How to Check if a Class Exists with JavaScript

Checking if a class exists on an element is simple and fast with the JavaScript classList property’s contains() method.

Let’s first take a look at the generic formula for using classList.contains() and then we’ll look at a practical use case.

classList.contains() formula

var element = document.querySelector("selector") element.classList.contains("class")

In the generic example above we use the versatile querySelector() method to find our target element via its selector name. The selector could be a class selector, element selector, or another selector type.

We then assign the element we found with querySelector() to our declared element variable.

Then we attach the classList property’s contains() method to our element via its variable reference. Then inside the contains() method’s argument (inside the parenthesis) we specify the name of the ‘class’ we want to check if exists.

Generic examples are boring, let’s get practical!

The Uncluttered News Feed

Filtering with classList.contains()
— a practical use case

You’re visiting a website with a mixed news feed of many different categories. But you’re only interested in reading about technology.

Cluttered news feeds are blasphemous. Let’s filter out all the other categories, using the classList.contains() method.

First, let’s add some HTML so we have some content to work with. Then we’ll style it quickly, and move on to the JavaScript.

HTML for our news feed

div class="wrapper"> h1>Newsfeedh1> div class="news-feed"> h3 class="headline"> a class="link category-health" href="#">Healtha> h3> h3 class="headline"> a class="link category-finances" href="#">Financesa> h3> h3 class="headline"> a class="link category-politics" href="#">Politicsa> h3> h3 class="headline"> a class="link category-nature" href="#">Naturea> h3> h3 class="headline"> a class="link category-humor" href="#">Humora> h3> h3 class="headline"> a class="link category-weather" href="#">Weathera> h3> h3 class="headline"> a class="link category-technology" href="#">Technologya> h3> h3 class="headline"> a class="link category-sports" href="#">Sportsa> h3> div> div class="fixed-container"> span>Filter:span> button class="btn-technology">Technologybutton> div> div> 

For our HTML content we have:

  • A big headline.
  • A news feed with different categories.
  • Outside of the news feed, we have a button called Technology. This is the button we’ll use to toggle (hide/show) all non-technology topics.

Obviously, our news feed example above only has a few news items (for illustration purposes), so it doesn’t look cluttered. But a real mixed news feed there would be a myriad of articles from each news category, flooding the feed. That’s when filtering buttons are useful.

CSS Styling

All the following CSS is cosmetic and optional, except the .js-hide class, which is a helper class we’ll use with JavaScript in the next segment.

body  font-family: "Source Sans Pro", "Helvetica", "Sans-Serif"; > .wrapper  position: relative; padding-left: 1rem; padding-right: 1rem; margin: 2rem auto; max-width: 50em; > .news-feed  border: 1px solid #eee; max-height: 256px; overflow-y: scroll; > .headline  font-size: 1.25rem; padding: 0.25rem 1.5rem; > .link  color: #252525; text-decoration: none; > .fixed-container  position: fixed; bottom: 0; left: 0; padding: 1.5rem; > .btn-technology  cursor: pointer; font-size: 1rem; padding: 0.5rem 1rem; margin-top: 2rem; margin-left: 1rem; border-radius: 4px; border: 1px solid #82b97e; outline: none; > .js-hide  display: none; >

Just make sure you add that .js-hide class to your CSS stylesheet and let’s move on to JavaScript!

The JavaScript

Copy and paste the following code into your JS file. I’ll explain how everything works right below.

var btnTechnology = document.querySelector(".btn-technology") var allNewsCategories = document.querySelectorAll(".news-feed .link") function showCategoryTechnology()  for (var i = 0; i  allNewsCategories.length; i++)  if (!allNewsCategories[i].classList.contains("category-technology"))  allNewsCategories[i].parentElement.classList.toggle("js-hide") > > > btnTechnology.addEventListener("click", showCategoryTechnology)

How the JavaScript code works

  • First we use querySelector() to grab our Technlogy button element via its class selector .btn-technology . which will act as the trigger for our filtering function later. We assign our button element to a variable called btn-technology .
  • Then we use querySelectorAll() to grab all our News Feed ( .news-feed ) items and select each item link by their class name ( .link ). We then assign all our news item links to a variable called allNewsCategories .
  • Then we create a function, showCategoryTechnology() <..>which we’ll call when the Technology button is clicked.
  • Inside the function body, we loop through all items () inside the News Feed element and store them in an array [i]
  • Inside the loop, we add a conditional if statement which says: “if any of the items on the list we just iterated through do not contain the class .category-technology — then run the classList.toggle method with the .js-hide class on those items.
  • On the last line, we attach the addEventListener() method to our button element. We tell the event listener to listen for a ‘click’ event. When the button is clicked, it calls the showCategoryTechnology() function, which runs the entire code block that makes this toggling feature possible.

The ! symbol (Logical Operator) that we put in front of allNewsCategories[i] is what handles the “not” part of our if statement. If you remove ! then our code will do the opposite of what it does now.

We could also have used classList.remove() to remove our unwanted news items. But in most cases, it makes sense to give our users the option of hiding/showing items, which is what classList.toggle() does.

Resources

Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Источник

Check If Class Exists JavaScript

In this tutorial we will learn how to Check If HTML Element of particular Class Exists using JavaScript. HTML DOM getElementsByClassName() method and .length property can be used for this purpose.

HTML Code

HTML Code is given below, in this code we have a paragraph tag with class red, we also have a button tag with onclick event.

My Class is Red

JavaScript Code

Take a look at the JavaScript code, the HTML Dom getElementsByClassName() method is used with .length property.

HTML Dom getElementsByClassName() is used to select all HTML elements with particular class.

.length property returns the length of a string. In this example it is used to count the number of selected elements with defined class (red).

If answer of elements.length is greater than 0, it means the class exist.

  

Another way to check this is by using the following code.

In above code .classList property is used which is used to return the class names as object.

.contains is used to check the class in the classList object. The answer of .contains is a Boolean value.

Demo

Video Tutorial

Источник

Check if Specific Class Exists on the Page Using JavaScript

During website development, sometimes programmers worry about why the desired outcome is not shown on the page, so they have to check whether the specific class is added to the particular page or element or not. To do so, JavaScript provides some methods for class verification of an element or a page, such as contains() method and the length property with the getElementsByClassName() method.

This blog will define the methods to determine whether the specific class exists on the page using JavaScript.

How to Check if Specific Class Exists on the Page Using JavaScript?

To verify if the particular class exists, use the following JavaScript methods:

Method 1: Check if a Specific/Particular Class Exists on the Page Using document.getElementsByClassName() With length Property

Use the “getElementsByClassName()” method with the “length” property to determine whether the particular class exists on the page or not. The getElementsByClassName() method is used for selecting the elements with the class name, and then it is checked to see if the collection’s length attribute is larger than 0. If it outputs “yes”, the class is present on the page.

Follow the given syntax for using the getElementsByClassName() method with the length property:

Pass the class name as a parameter that needs to be verified.

Example

In an HTML file, first design the page. Here, we will add an image as a logo on the header by using a div element and tag:

src = «https://linuxhint.com/wp-content/uploads/2019/11/Logo-final.png» alt = «» / >

Then, set the title on the header:

< p class = "sec" >Check if Specific Class Exists on the Page Using JavaScript

After that, create a button on the page that will call the “checkClassExists()” function which tells whether the specific class exists on the page or not:

Executing the above HTML code gives the following page on the browser:

Now, in the JavaScript file or the tag, use the following code:

const classCheck = document. getElementsByClassName ( ‘flex-item1’ ) . length > 0 ;

alert ( ‘✅ class «flex-item1» exists on page’ ) ;

alert ( ‘⛔️ class «flex-item1» does not exist on page’ ) ;

  • First, define a function “checkClassExists()” that will trigger the button click.
  • Create a variable that stores the result to check the class “flex-item1” by using the “getElementsByClassName()” method and then check to see if the collection’s “length” attribute is larger than 0.
  • Now, show an alert message for class existence and not existing on the page.
  • If the resultant value in the variable is greater than 0, it shows “class “flex-item1″ exists on page”.
  • Else, an alert message will show “classflex-item1″ does not exist on page”.

To verify if the specified element contains the particular class in JavaScript, check the next section.

Method 2: Check if the Specific Class Exists on the Page Using contains() Method

To determine whether a particular class exists on a web page, use the “contains()” method of the “classList” property. Pass the class name in the contains() method, and it gives true if the class name exists in the specified element else, it returns false.

Use the following syntax for the contains() method:

Example

As we know, all the content of the web page is inside the tag, so we will first fetch the body element using its assigned id:

Define a function and fetch the body element by passing the assigned id “pg” in the “getElementById()” method, then calls the “contains()” method by passing the class “divStyle” to check whether this class exists in the entire tag or not:

const classCheck = document. getElementById ( ‘pg’ ) ;

if ( classCheck. classList . contains ( ‘divStyle’ ) ) {

alert ( ‘✅ class «divStyle» exists on page’ ) ;

alert ( ‘⛔️ class «divStyle» does not exist on page’ ) ;

The output shows that the “body” element/tag does not contain the “divStyle” class:

We have compiled the essential information related to verifying a particular class on the page using JavaScript.

Conclusion

To determine if the particular class exists on the page, utilize the “document.getElementsByClassName()” method with the “length” property or the “contains()” method. The first method is the most commonly used for this purpose. The contains() method is used for any specific element. In this blog, we defined the methods to determine whether the specific class exists on the page using JavaScript.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Читайте также:  Junior javascript разработчик зарплата
Оцените статью