Can you reference document.styleSheets[].cssRules[] by specifying a rule name?

I am trying to modify a specific class property value in JavaScript without using an integer as a pointer or looping through all classes to find a matching selectorText value.

This is specifically for changing the language displayed on the webpage.

<style id="languages" class="languages" title="languages">
<!--
    /* ... more styles ... */

    .lang-ita { display : none; }
    .lang-eng { display : none; }

    /* ... more styles ... */
-->
</style>

<script language="javascript">
<!--
    function fxSwitchLanguage(i)
    {
        /* ... more code ... */

        document.getElementById('languages').sheet.cssRules[i].style.setProperty('display','block');

        /* ... more code ... */
    }
-->
</script>

<button onClick="fxSwitchLanguage(0);">ITA</button>
<button onClick="fxSwitchLanguage(1);">ENG</button>
<br>
<div class="lang-ita">CIAO!</div>
<div class="lang-eng">HELLO!</div>

Instead of using ".cssRules[i]", I would like to be able to reference the class directly by name like ".cssRules['.lang-eng']".

Since this document may be edited by others, I prefer to avoid hard-coded integers for stability and do not want to loop through all classes to match selectorText properties.

I am open to accommodating browser differences (.cssRules or .rules).

I am simply looking for a way to achieve this functionality in the manner I described.

Answer №1

Unfortunately, there is no CSSOM API available to retrieve a rule (or a list of rules) by its selector string directly. The only way to achieve this is by iterating through the rules until you find the one you need. While this may not be the most efficient approach, it can be done outside of the fxSwitchLanguage function and just once when the script loads. It's recommended to store references to the relevant rules in constants or a data structure for easy access.

If your objective is to manipulate the rules using JavaScript, an alternative approach would be to actually create these rules using JavaScript as well. This way, you can easily maintain references to them without the need for iteration.

const {sheet} = document.getElementById('languages');
const rules = new Map(['eng', 'ita', 'esp'].map(lang => {
  const rule = sheet.cssRules[sheet.insertRule(`.lang-${lang} {
    display: none;
  }`)]; // The insertRule method returns an index
  return [lang, rule];
}));

let active = null;
function fxSwitchLanguage(l) {
  if (active) rules.get(active).style.display = 'none';
  rules.get(l).style.display = 'block';
  active = l; 
} // Alternatively, you can implement a toggle functionality

<style id="languages">
</style>

<button onClick="fxSwitchLanguage('ita');">ITA</button>
<button onClick="fxSwitchLanguage('eng');">ENG</button>
<button onClick="fxSwitchLanguage('esp');">ESP</button>
<br>
<div class="lang-ita">CIAO!</div>
<div class="lang-eng">HELLO!</div>
<div class="lang-esp">HOLA!</div>

Answer №2

Here is an interesting idea from a comment:

function updateLanguage(language) {
  //* Remove existing language settings if they already exist */
  if (document.contains(document.getElementById("langSetting"))) {
    document.getElementById("langSetting").remove();
  }
  //* Update the chosen language */
  var newStyle = document.createElement("style");
  newStyle.setAttribute("id", "langSetting"); //* Add an identifier */
  var addContent = ".lang-" + language + "{display:block;}";
  newStyle.appendChild(document.createTextNode(addContent));
  var head = document.getElementsByTagName("head")[0];
  head.appendChild(newStyle);
}
[class^='lang'] {display:none;}
<button onClick="updateLanguage('ita');">ITA</button>
<button onClick="updateLanguage('eng');">ENG</button>
<hr>
<p class="lang-ita">CIAO!</p>
<div class="lang-eng">HELLO!</div>

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

Having trouble with AngularJS UI Router failing to load template and controller?

I am currently trying to identify the error in my code. Whenever I access /dashboard, it only loads the template from the first route, which is defined as SYSTEM_VARS.includes.general.root. However, it does display the console.log message inside the resolv ...

Transforming a JSON object into a list in C#

After exploring similar posts without success, I am reaching out here for help. I have a Json data stored in a hidden field that I am trying to access in the code behind file of my markup page. My goal is to convert this Json into a List and bind it to a ...

Returning Props in Dynamic Components with Vue 3

Exploring the capabilities of Vue3's Dynamic Component <component>, I am currently working with this setup: Component 1: <template> <div> <h1> Name Input: </h2> <Input :model="props.name" /> ...

What is the best way to explore JavaScript text using Firebug?

The search function (magnifying glass) located at the top-right hand corner of Firebug does not have the capability to search within JavaScript blocks. For instance, if I have the following code snippet: <script type="text/javascript"> var fooBa ...

Several different factors

I need to develop a form that allows users to edit existing comments. The form will display a textarea containing the old comment text and a submit button. My goal is to send the newComment data via ajax to another script. However, I am facing an issue w ...

Calling Node Express request inside a GET route

I am currently utilizing nodejs as an intermediary layer between my public website and an internal server within our network. Through the use of express.js, I have created a basic REST api where the endpoint should trigger a request call to a webservice a ...

Tips for utilizing Vue 'component' with just Vue added as a page add-on using <script>:

I am trying to incorporate a Vue component called vue-timeago: import VueTimeago from 'vue-timeago' Vue.use(VueTimeago, { name: 'Timeago', // Component name, `Timeago` by default locale: undefined, // Default locale locales: { ...

Struggling with creating and exporting TailwindCSS and NextJS

I'm encountering challenges in constructing and exporting my TailwindCSS and NextJS project. While everything works smoothly when running `npm run dev` with all Tailwind classes functioning properly, I face an issue when executing `npm run build && np ...

Is it possible to constantly retrieve data at one-second intervals in NextJS using getServerSideProps?

Is there a way to continuously fetch API data in NextJS using SSR (getServerSideProps) every second? This would involve the client making a request to the server every one second to receive the most up-to-date API data. Any suggestions? export const getS ...

Unable to perform a default import in Angular 9 version

I made adjustments to tsconfig.json by adding the following properties: "esModuleInterop": true, "allowSyntheticDefaultImports": true, This was done in order to successfully import an npm package using import * as ms from "ms"; Despite these changes, I ...

How come the Qunit counter doesn't seem to ever reach its expected target value during this test?

I'm currently stuck on a Qunit test related to jQuery Mobile's listview.filter extension. I can't figure out how the variable _refreshCornersCount ends up with a value of 3. Below is the section causing confusion. module( "Custom search ...

Setting form values using Angular 9

I am currently facing a challenge that I could use some assistance with. My dilemma involves integrating a new payment system, and I seem to be encountering some obstacles. Here is a snippet of what I have: options: PaystackOptions= { amount: 5000, emai ...

Tips for retrieving data from a database with just one key press

There is a text field that triggers a JavaScript function when a key is pressed. <input type="text" class="text" id="txt_sh_vid" onKeyPress="vhc_record()" maxlength="4"> The function takes the input from the text field and searches for a result in t ...

Angular Bootstrap UI - Ensuring only one element collapses at a time

I have integrated the angular bootstrap UI library into my website by following this link: https://angular-ui.github.io/bootstrap/ One issue I am facing is that when I implement a collapsible feature using this library, it collapses or expands every eleme ...

Tips for creating a Vuex mutation without using asynchronous promises

I have a project underway that involves building an app using Vue.js, Vuex, and Firebase to update data from Firestore database to the state in mutations. Even though mutations are synchronous and promises (.then) are asynchronous, my current implementat ...

The onsubmit function is not functioning correctly in combination with Ajax

My current implementation involves utilizing Ajax and Php for user login validation. Unfortunately, the form onsubmit function is not properly functioning. <form action="loggedin.php" onsubmit="return test()" method="post"> Below is the correspondi ...

Rendering a Nativescript component once the page has been fully loaded

I'm currently working on integrating the WikitudeArchitectView into my TypeScript code. I've successfully registered the element in the main.ts TypeScript file: var architectView = require("nativescript-wikitudearchitectview"); registerElement ...

Is it possible to include number padding in a Bootstrap number input field?

When using an input box like this: <input type="number" class="form-control" value="00001" /> Is there a way to make it so that when the arrow up key is pressed, it changes to 00002 instead of just 2? https://i.sstati ...

How to retrieve the third party child component within a Vue parent component

Within my example-component, I have integrated a third-party media upload child component called media-uploader: <example-component> <form :action= "something"> // Other input types <media-upload :ref="'cover_up ...

Perform JavaScript Actions upon Submission of a Stripe Form

I have implemented a custom checkout button for Stripe and I am looking to trigger a JavaScript function after the checkout process is successfully completed. Specifically, I want the function to change the style of the "book-appointment-button" from "no ...