Skip to main content

Command Palette

Search for a command to run...

Check if a DOM element has a specific class or attribute

Published
•1 min read•View as Markdown

In jQuery, you can check if an element has a class using the hasClass() function. The equivalent in JavaScript is classList.contains() function. In jQuery, you can check if an element has a specific attributre using the attr() function. The equivalent in JavaScript is hasAttribute() function.

Refer to the following code snippet to learn how to check if an element has a class through jQuery and vanilla JavaScript:

To check for class

// Check if element has a class using jQuery
if ($(".blog-post").hasClass("popular")) {
    alert('This is a popular post');
}
// Check if element has a class using vanilla JavaScript
if (document.querySelector(".blog-post").classList.contains("popular")) {
    alert('This is a popular post');
}

To check for attribute:

// Check if element has a class using jQuery if ($(".image").hasAttribute("title")) { alert('This is an image with a title'); }

// Check if element has a class using vanilla JavaScript if (document.querySelector(".image").hasAttribute("title")) { alert('This is an image with a title'); }

More from this blog

I

Is A Web Learning

54 posts