Can someone help me understand how to change the structure in order to identify which class has a body?

I have a small example to share with you:

link

HTML CODE:

<div class="body">
    <div class="test">TEST</div>
</div>

JS CODE:

switch (className) {   //instead of n, I need to write className
    case body:
        alert("my class is body");
        break;
    case another_class:
        alert("my class is another");
        break;
    default:
        //etc
}

I simply want to test if my class exists one at a time using a switch statement.

Each page on my site has different classes in the body, and I want to apply styles only if a certain class is present...

I hope I have explained my idea clearly, if not, please let me know.

Thank you in advance!

Answer №1

an example using jQuery could be:

if($('.body').length){
    alert('this is the body');
}
else if ($('.another_class').length)
{
    alert('another class detected');
}

Answer №2

Here is a sample code snippet for you to use:

switch (document.querySelector('div').classList[0]) {
    case "body":
        alert("my class is body");
        break;
    case "another_class":
        alert("my class is another");
        break;
    default:
        //etc
}

Check out this fiddle for a live demo.

Answer №3

$('div').each(function(){
var className=$(this).attr('class');
switch (className) {
    case "content":
        alert("class is +"className);
        break;
    case "example":
        alert("class is +"className);
        break;
    default:
        //additional code
}
});

Perhaps this can be useful.

Answer №4

It's not clear what your goal is, but you can add a specific style to a child element based on the parent element's class without using any javascript. Simply define your CSS like this:

.body .test{
   style the test inside .body regardless, can be overridden by subsequent rules ;)
}
.body.classNameA .test{
   style the test if classNameA is present;
}
.body.classNameB .test{
   style the test if classNameB is present;
}

If the .body class is the only thing changing, you can omit it.

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

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

Dealing with functions that may not consistently return a promise

When dealing with a situation where a function does not always return a promise, how can it be best handled? The complexity of my current code prevents me from providing a detailed explanation, but essentially, the issue involves checking a condition and t ...

Safari is currently experiencing compatibility issues with iPad, resulting in a malfunction

I encountered a unique issue with my most recent website project. The website is built on WordPress, and the custom theme I created is presenting an unexpected problem: Despite functioning perfectly on all browsers and devices, the site fails to display p ...

Setting a default value for a select option in Angular 2

I am trying to set a default value for an option, acting as a placeholder using this method. It works in pure HTML, but when I implement it with the *ngFor attribute in Angular 2, nothing is selected. Here is the code I use in pure HTML: <select name= ...

express node struggling to locate bootstrap.js file

I am working with a specific directory structure within my project: projectName | -.sencha/ | - app/ | - view | - controller | - store | - saas | - server/ | -server.js ...

Functional Components with Methods in ReactJS

When creating a functional stateless component that requires methods to access props, is there a recommended approach or best practice to follow? For instance: function Stateless(props) { function doSomething(props) { console.log(props); } ...

Is there a way to synchronize breakpoint values across different media queries?

Currently utilizing Next.js version 9.53. Utilizing the built-in CSS module support provided by Next.js without the use of CSS pre-processors (less, sass, etc.) or CSS-in-JS (styled-components, etc.). Presently, my approach involves writing CSS in a mobi ...

How can I display table rows along with their child table rows in Angular?

Is there a way to display API data in a table using Angular? The table should have collapsible rows with nested child rows. This is the JSON file structure: { "collapse1": [ { "name": "Soil", "budget": 12345, "child": [ { ...

Integrating jquery events and functions with angularjs

Recently, I've come across this piece of code: $('.btn').click(function() { $(this).removeClass('big-red-button'); $(this).addClass('btn-loading'); $(this).find('.text').text('Working..'); ...

Variations between <div/> and <div></div>

When using Ajax to load two divs, I discovered an interesting difference in the way they are written. If I write them like this: <div id="informCandidacyId"/> <div id="idDivFiles"/> Although both divs are being loaded, only one view is added ...

Tips for testing the onEnter and resolve functions of a ui-router state

I need help testing an Angular UI Bootstrap modal that is triggered from the onEnter function in the state below: .state("profile.index.edit.services", { url: "/edit/services/:serviceCode", parent:"profile.index", onEnter: ['$ ...

Learn how to retrieve the value of an associated field at a specific index by utilizing a combo box in JavaScript when receiving a JSON response

Hey there, I'm currently working on a phone-gap app where I need to fetch data from a WCF service that returns JSON responses. Specifically, I want to display the DesignName in a combo box and pass the associated designId. Any thoughts on how I can ac ...

Tips for halting the live graph plotting based on a specific condition with canvas js

I have a piece of code that generates a live graph based on probabilities. I am looking for a way to stop the plotting process as soon as a specific condition is met. <script> window.onload = function () { var dps = []; // dataPoints var c ...

Using AngularJS to automatically fill in HTML select fields

Encountering an issue with an HTML select element in AngularJS. The API response returns one of the values as an integer, however, setting the "value" attribute for autofill is proving to be a challenge. Below is a screenshot showcasing the data received ...

Why won't console.log function execute in this particular situation?

(function( $ ){ $.fn.openlayers = function( mapElementId, options ) { alert(console.log); console.log(options); ... } }); While attempting to enhance the capabilities of a JavaScript library, I encountered an unexpected issue. ...

having difficulty showing the column filter feature in the DataTable

I am currently utilizing a datatable and in need of an individual column-based search feature along with a global search. I am working with a 2D array. The search boxes are being displayed, however, the search functionality is not functioning correctly fo ...

The alignment of the list is off when using Flexbox on smaller screens

When my flexbox shifts into a column layout at 600 pixels, the list in the second box loses its center alignment on smaller screens. Despite trying various margin and padding adjustments within and outside of media queries, the content remains too far to t ...

Retrieve items in Angular by sending a POST request

I am currently developing my first application using Angular and have encountered a challenge. I have the address for a POST request with an authentication token, structured like this: http://example.com/orders?authentication_token=123456 I need to imple ...

Unexpected absence of Aria tags noticed

I've been working on integrating ngAria into my project. I have injected it into my module and created the following HTML: First Name: <input role="textbox" type="text" ng-model="firstName" aria-label="First Name" required><br> Employee: ...

Automatically launch a popup window specified in JavaScript

Aim:- I am trying to automatically open a radwindow from the server-side based on a specific IF condition. Snippet Used:- In the aspx page, I have defined the radwindow as follows: <telerik:RadWindowManager Skin="WBDA" ID="AssetPreviewManager" Modal= ...