Retrieve the stylesheet based on the presence of a specific class

Is there a way to dynamically add a CSS stylesheet based on the presence of a specific class on a page?

For example, instead of checking the time and loading different stylesheets, I want to load different stylesheets depending on the class present in the HTML:

<script>
<!--
function getStylesheet() {
    if(document.body.classList.contains('company')) {
       document.write("<link rel='stylesheet' href='company.css' type='text/css'>");
    }
    if(document.body.classList.contains('contact')) {
       document.write("<link rel='stylesheet' href='contact.css' type='text/css'>");
    }
    if(document.body.classList.contains('enterprise')) {
       document.write("<link rel='stylesheet' href='enterprise.css' type='text/css'>");
    }
    if(document.body.classList.contains('media')) {
       document.write("<link rel='stylesheet' href='media.css' type='text/css'>");
    }
}

getStylesheet();
-->
</script>

This script will check for the presence of specific classes like "company," "contact," "enterprise," or "media" in the body element and then load the corresponding CSS file.

Answer №1

If you want to check if a certain class is present on a webpage using jQuery, you can do so by implementing the following code snippet:

if ($('.class').length){
    // Your code here
}

Simply replace .class with the specific class name you are looking for.

For example:

if ($('.company').length){
    document.write("<link rel='stylesheet' href='company.css' type='text/css'>");
}
if ($('.contact').length){
    document.write("<link rel='stylesheet' href='contact.css' type='text/css'>");
}
and so on...

Answer №2

For those utilizing jQuery, a highly recommended tool:

var types = ['organization', 'individual', 'corporation', 'press'];
for (i in myTypes) {
    if ($('.' + types[i]).length) {
        applyStyle(types[i])
        break;
    }
}

Answer №3

Avoid splitting your stylesheets into multiple files as it does not offer any advantages. Instead, maintain all your styles in a single stylesheet and apply them to the page elements using classes on <body> or <html>. Let me illustrate with a brief example.

<body class="page-product">

Then write

.page-product h1 { }

and so forth.

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

How can a JQuery slideshow be programmed to only iterate once?

Looking to create a slideshow that transitions between images every two seconds? Check out the code snippet below: HTML: <div class="fadeIn"> <img src="img/city.png" class="remimg" id="city"> <img src="img/shop.png" class="remimg" ...

Res.redirect() function does not redirect the browser URL as expected when triggered by a request made through a frontend fetch() call

Encountering a new issue that is challenging me. In the backend, there is an API route that redirects the browser URL to /signin using res.redirect('/signin'). Upon this redirection, React Router triggers the rendering of a 'log back in&apos ...

Unable to loop through the "dataList" retrieved from a service call to the java backend within an Angular 9 application

After receiving JSON data from a Java backend service called houseguidelines, the information is sent to an Angular application via a service call. I am attempting to iterate over this returned JSON data and add it to an array I have created. Unfortunately ...

Inaccurate audio timestamps in Chrome

I am currently working on a web application that features an audio component sourced from a local .mp3 file lasting approximately 1 hour. I have encountered an issue where, upon clicking the seekbar to jump to a specific point in the audio (e.g., 00:01:00) ...

Managing JSON data through AJAX in ColdFusion

For my external API call using AJAX, I am incorporating a local API setup as an intermediate step. The process is as follows: The Ajax call sends data to localAPI.cfm. Within localAPI.cfm, there is a <cfhttp> tag to forward the data to an external ...

Using React js to create a blurred background effect when an input field is in focus

I would like to implement an input field similar to the one shown in the image. When the input field is clicked on, I want to blur the background. image example Do I need to use a specific library for this? Currently, I am using Material UI. ...

Retrieve data from each URL listed in a JSON array using React

My json file structure was as follows: [ { "name": "google", "route": "/google", "url": "www.google.com" }, { "name": "bing", "route": " ...

What is the best way to efficiently transmit Objects through AJAX utilizing bodyParser in node.js express?

Currently attempting to execute: $.ajax({ type:"POST", url:"/psychos", data:JSON.stringify(this.psycho) }) Upon reaching the server, I encounter the following: app.post("/psychos", function(request, respon ...

Converting dynamic content within a div into an interactive link

I am currently working with Longtail's JW Player and facing some difficulties with a basic function. Since I am not familiar with the programming language terminologies, I will describe the issue step by step: There is a JavaScript code that displays ...

Implementing concurrent operations in React Native using Firebase, combining async/await with Promise.all

import fire from '../config/fire'; const db = fire.firestore(); class InitialDb extends Component { constructor(props) { super(props); this.state = { schools: '', students: '', }; } async compo ...

What is the function of the next and back buttons in AngularJS?

I need assistance with creating next and previous buttons in Angular. As I am new to programming, I have written a program that works when using a custom array $scope.data = []. However, it doesn't work when I use $http and I would appreciate any help ...

Having trouble deciphering mathematical formulas while editing content on ckeditor

While using math formulas in CKEditor, I noticed that when I insert new content via textarea, the formulas are displayed correctly. However, when I go back to edit the content, the text formulas do not display as before. This is the source code I am using ...

Problem with Ionic 2 local storage: struggling to store retrieved value in a variable

Struggling to assign the retrieved value from a .get function to a variable declared outside of it. var dt; //fetching data this.local.get('didTutorial').then((value) => { alert(value); dt = value; }) console.log("Local Storage value: " ...

Building a React Typescript service with axios functionality

When creating a service and calling it from the required functional component, there are two different approaches you can take. 1. export const userProfileService = { ResetPassword: async (userId: string) => { var response = await http.get ...

Issue with using bind(this) in ajax success function was encountered

In my development process, I utilize both react and jQuery. Below is a snippet of the code in question. Prior to mounting the react component, an ajax request is made to determine if the user is logged in. The intention is for the state to be set when a ...

Vue.js / Nginx / Node.js - Error 413: Payload Too Big

My frontend is built using Vue.js and is hosted on an nginx server in production. Here's a snippet of my nginx.conf configuration: server { listen 80; server_name localhost; root /usr/share ...

Blazor Shared CSS File

Currently, I have successfully implemented 2 pages in my Blazor app: Login.razor located in the Auth folder AddPerson.razor situated in the Profile directory At this point, I have managed to integrate a CSS file specifically for the AddPerson.razor page ...

The code is functioning properly, however it is returning the following error: Anticipated either

Can you explain why this code is resulting in an unused expression error? <input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e =>{(e.key ==='En ...

Encoding and Displaying Characters in HTML with UTF-8

I am experiencing an issue with UTF-8 characters in the page title. I would like to include the music symbol ♫ on the page title. The strange thing is that sometimes it displays correctly (in Google Chrome) and other times it shows a square symbol indic ...

`Enhancing Navigation Links with Scroll-Activated Styling`

I'm attempting to recreate a visual effect that is similar to: Specifically, I am trying to achieve a style where the links in the navigation bar change color when the corresponding section is displayed, such as having the gallery link in the navbar ...