What is the best way to validate a particular class in javascript?

Need help checking if a specific id has a particular class. Unsure of the process?

Here's the code snippet where the attempt at checking the id for a specific class is visible within the homeTransition function.

function homeTransition()
    {   
        // Code snippet for checking specific class on a specified id
    }

function aboutTransition()
    {   
        // Code for aboutTransition function
    }

function projectsTransition()
    {   
        // Code for projectsTransition function
    }

function contactTransition()
    {
        // Code for contactTransition function
    }

//Menu
function expand(){
  // Code to expand the menu
};
$(".button").on('click', expand);
 CSS code block 
 HTML code block 

Answer №1

To confirm this, you can follow these steps:

Verify if the class "animated" exists in the "projectsContent" element's className property by using the following code:
document.getElementById("projectsContent").className.indexOf("animated") !== -1

If you need to check for multiple classes, consider storing the className in a variable and checking for each class individually or create a utility function.

UPDATE:

Alternatively, as suggested by @Jerinaw in a comment, you can use the shorter code snippet below if you do not require support for < ie10:

document.getElementById("projectsContent").classList.contains("animated") // class exists on element

Answer №2

Opt for pure Vanilla JavaScript

document.querySelector('#aboutContent.myclass');

This means: Locate the element with the id (id selector #) aboutContent, and with the class (class selector .) myClass.

Take a look at
CSS selectors
querySelector

Furthermore, it appears you are blending Vanilla JavaScript and jQuery. It might be beneficial to learn more about selecting elements with jQuery.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transforming CSS Styles of Elements with Bootstrap

After incorporating links and scripts for Bootstrap v4.5 into my project, I quickly noticed that it automatically overrides the styles of text, buttons, and other elements I had previously customized. While I added a Bootstrap alert for authentication pur ...

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

Sorting an array of objects keys according to the position of keys in another array

I have two arrays: one with the correct order of keys and values, and another array coming from a backend in an unsorted format. let arr1 = ['name', 'age', 'occupation', 'address'] let arr2 = [{'age': 20, ...

Error: The variable success_msg has not been defined in the EJS Reference

I am in the process of developing a library website for my school that includes login and administration capabilities. I am relatively new to node.js and EJS, but I recently revamped the routing and page delivery system to use EJS and express. As part of u ...

Is there a way to retrieve the id attribute of an option element from the source component?

When a user makes a selection, I am trying to access the id attribute of the HTMLOptionElement. However, it always returns 0 instead of the actual id I passed (such as 1 or 2) from the select tag: <div class="col-8"> <select (cha ...

Looking for solutions to manage mouseenter, mouseleave events and ensuring content dropdowns stay visible in Vue.js 2?

Hey there, I'm trying to figure out how to keep dropdown content from disappearing when using @mouseenter and @mouseleave. Here's what I have so far: <div class="wrapper"> <div class="link" @mouseenter="show = ...

I am frustrated because the csvtojson converter keeps replacing my file name with "undefined."

Despite running the csvtojson module on node.js successfully without any additional code, I encounter an issue when attempting to include it within a function. The result returns as undefined, even though the file path remains intact. Check out the JavaSc ...

What is the best way to transfer Django variables to HTML?

Looking to send data from the rs232 port and showcase it in a graph using javascript? Check out this resource: Seeking guidance on importing the views.py variable into my html file. views.py import io from django.http import HttpResponse from django.shor ...

The md-select search filter currently functions according to the ng-value, but it is important for it to also

I am using a md select search filter with multiple options available. For instance: id: 133, label:'Route1' id: 144, label:'Route2' id: 155, label:'Route3' id: 166, label:'Route4' If I input '1' ...

Combining NPM Script Commands: A Comprehensive Guide

I am aware that NPM scripts can be chained using &&, pre-, and post- hooks. However, I am wondering if there is a way to simply break down lengthy script lines into a single, concatenated line? For instance, can I convert the following: "script": ...

What could be causing this empty Ajax ResponseText?

$("b_xml").onclick=function(){ new Ajax.Request("books.php", { method:"GET", parameters: {category:getCheckedRadio(document.getElementsByName("category"))}, onSuccess: showBooks_JSON, onFailure: ajaxF ...

Customizing Big Cartel's Neat theme: A guide to eliminating the blur effect on featured product images upon site activation

My website is built on Big Cartel using the Neat theme. Every time the homepage loads, the Featured products images appear blurry for about 4 seconds, especially if you're not using Chrome browser. Is there a way to remove this blur effect? Thank yo ...

Utilize image maps for dynamically displaying and concealing div elements

Here is the current state of my code... VIEW DEMO I am aiming to display the blue text to the user only when they click on the blue circle, etc... I believe I need to modify the attributes of the div elements, but I am not very familiar with jQuery and ...

Tips for disabling automatic sliding in Bootstrap 5 carousel specifically on larger screens

I am working with a Bootstrap 5 carousel that I need to configure to stop autosliding on large screens, but maintain autoslide functionality on mobile devices. Is there a way to achieve this using only HTML and CSS/SCSS? I am aware of the data-bs-interval ...

Customizing number input types in Angular 2 - the perfect solution

Attempting to incorporate a time picker using HTML5 input type number in Angular2. The code snippet below illustrates the setup: <input type="number" [(ngModel)]="hour" (change)="checkHours();" name="one" min="1" max="12"> <input type="number" ...

Navigating to an offline HTML webpage using JavaScript in a PhoneGap application

I am currently developing a phonegap application. I am attempting to create a login feature where upon clicking the submit button on the Login.html page, I should be directed to a local HTML file. Login.html <tr> <td>&nbsp;</td> ...

React - retrieving the previous page's path after clicking the browser's "back" button

Imagine I'm on Page X(/path-x) and then navigate to page Y(/path-y). Later, when I click the "back" button in the browser. So my question is, how do I retrieve the value of /path-y in PageX.tsx? Note: I am utilizing react-router-dom ...

Challenges with Bootstrap input groups

Despite trying various solutions, nothing seems to be working for me. I attempted using width:200px, but the issue persists. Since my form was quite outdated, I decided to switch to a bootstrap version. However, while others are able to resolve the issue w ...

How can the table attribute "name" be obtained and added as the file name for DataTables in the export feature?

Having multiple tables on my page using JQuery DataTables, I find it to be a useful library. I am looking to modify the file name for exporting the data on these tables. I have several DataTables on this page This is how I initialize my tables: $(docume ...

"Can you provide guidance on binding data in vue.js when there is a dash (-) in the key of the JSON

My JSON data is structured as follows: { "color-1": "#8888", "color-2": "#000" } I am attempting to bind this variable with a style tag for a Vue component. However, my current approach seems to not be functioning as expected. <div v-bind:sty ...