Incorporate dynamic rules into a CSS stylesheet

I am trying to dynamically add a rule to my CSS for each element. Each rule should have a different background-image and name. However, I seem to be encountering an issue where the dynamically added div is not linking to the dynamically added CSS rule. I'm unsure where I may have gone wrong.

$(document).ready(function () {

var stylesheet = document.styleSheets[0];

var url = '/Home/PrikaziTipoveLokacija';

//I am fetching data from the database using Ajax
$.ajax({
    type: "GET",
    url: url,
    cache: false,
    success: function (data) {
        //Counting the number of rules in my CSS before adding new rules
        for (var i = 0; i < stylesheet.cssRules.length; i++) {
            count++;
        }
        alert(count); //This returns a count of 16 (CSS file has 16 rules)
        count = 0;            

        //Adding a rule to CSS for each element in the data
        for (elem in data) {
            if (stylesheet.addRule) {
                stylesheet.addRule(data[elem].Kljuc + '_ikona', '{ background-image: url("../Images/mesnicaicon.png"); background-size: cover; background-repeat: no-repeat;}');
            } else if (stylesheet.insertRule) {
                stylesheet.insertRule(data[elem].Kljuc + '_ikona' + '{' + 'background-image: url("../Images/mesnicaicon.png"); background-size: cover; background-repeat: no-repeat;' + '}', stylesheet.cssRules.length);
            }
        }

        //Checking the number of rules in CSS after adding new rules
        for (var i = 0; i < stylesheet.cssRules.length; i++) {
            count++;
        }
        alert(count); //This returns a count of 33, so the new rules are added (Data has 17 elements, so, 33-16=17)
        count = 0;

        //Creating div elements for each data element and appending them to the container
        for (elem in data) {
            var div = document.createElement('div');
            
            div.className = 'ikona'; //Class for styling
            div.id = data[elem].Kljuc + '_ikona'; //Setting a unique ID
            
            var onclick = document.createAttribute("onclick");
            onclick.value = 'prikaziTipLokacije('+ data[elem].ID +')'; //Defining the onclick function
            div.setAttributeNode(onclick);

            div.innerHTML = data[elem].Naziv; //Displaying the text
            
            document.getElementById('izbornik_za_lokacije').appendChild(div); //Appending to the container
        }
    },
    error: function () {
        alert("Error fetching location types");
    }
});
});

The rule is not being appended as expected.

https://i.sstatic.net/ODF63.jpg

Answer №1

let customStyle = document.createElement('style');
customStyle.innerHTML = '*{ color:blue; } /* Your custom styles here */';
document.body.appendChild(customStyle);

Generate a new style element and apply it to the document

This snippet was tested on Stack Overflow (execute from the console) and produced the desired result

document.styleSheets[0].insertRule('* { color: blue; }')

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

Another drop-down is hiding the bootstrap-select drop-down from view

What could be causing some parts of the first drop-down menu to be hidden by another drop-down menu below in the code snippet provided? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv= ...

What is causing this animation to malfunction?

Could someone assist me in hiding this div-container for a brief period of 2 seconds? If you have any alternative suggestions, feel free to share them but, please refrain from using jQuery or JavaScript. #vcontainer { height: 450px; width: 100%; ba ...

Executing an SQL delete query with a button click using a JavaScript function in PHP

I have created a setup with three essential files - index.html, database.php, and function.js. In database.php, there is a form generated containing a delete button that triggers the deletion SQL query when clicked. The primary objective is to present a ta ...

Eliminate duplicate time slots in Laravel and Vuejs

Currently, I am delving into laravel(5.2) and vuejs as a newcomer to both frameworks. My goal is to utilize vuejs to eliminate redundant time slots. In my blade file, the code looks like this: <div class="form-group"> <label for="form-fi ...

Enhancing Your Website with Multiple Background Images in CSS3

Having trouble understanding how to position multiple background images with CSS3. I'm struggling to get them to display at the top, middle, and bottom of the page. Can you help me figure out how to make an image appear at different positions using a ...

Adding the Edit action in React-Redux is a crucial step towards creating a dynamic

I am looking to add an edit action to my blog page in addition to the existing ADD, DELETE and GET actions. Any suggestions on how I can implement the EDIT action to make my blog editable with just a button click? Your help would be greatly appreciated. ...

Using dual ngFor in Angular 4: A step-by-step guide

I am encountering an issue in my Angular 4 project where I receive two different arrays in response to a server request, and I want to utilize both of them in the template. Here is my controller code: this.contractService.getOwnerContract() .subscribe( ...

Performing JavaScript functions after fetching an XSLT page via AJAX

Is there a way to trigger JavaScript at a particular time without relying on setInterval() or onClick()? The issue I'm facing is that when I click to load an XSLT page using Ajax, the JavaScript within it does not execute even though it's writt ...

What methods can I use to emphasize three distinct dates?

I'm facing difficulty highlighting three specific dates: "10-11-2020", "22-11-2020", and "07-11-2020" using React.js and Datepicker. Unfortunately, my attempts have not been successful so far. Here is the code snippet I am working with: import React, ...

Storing the value of the current vertical scroll position in a variable using jQuery

I'm currently dealing with a challenge that involves using the value of (window).scrollTop() as a crucial variable in my project. What I aim to accomplish is to retrieve and utilize the specific scroll value at a particular moment within an if stateme ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

The jQuery Ajax function seems to be malfunctioning, while the PHP code is executing smoothly without any

I attempted to utilize AJAX to send form data to a .TXT file using PHP code. The information is successfully being added to the text file, however, the AJAX functionality is not functioning properly. Can someone please point out the error in my code? ...

Is it necessary to encapsulate Factory calls within a function in my Controller file?

Typically, I call a Factory from my Angular controller directly within the controller function without creating a separate method. For instance: (function () { 'use strict'; angular.module("Dashboard") .controller("DashboardController", D ...

Effective steps after Ajax request

Whenever a user clicks the "like" button, I perform a check in the database to see if they have already liked the photo. This check is done using ajax. If the photo has already been liked, the success message will indicate "already liked", otherwise it wi ...

Encountering an error saying "Cannot read property 'x' of null when using Google Charts LineChart"

When I hover over the legend labels on my Google chart, I keep getting an error message that says "Cannot read property 'x' of null," and I'm not sure why. The data is all in JSON format from an AJAX GET request and does not contain any nul ...

Changing the appearance of a radio button dynamically upon clicking

I am currently working on a dynamic pickup date form that utilizes radio buttons. My goal is to change the style of the selected value when a user clicks on it. Below is the code I have tried, but it has not been successful: foreach ($period as $day){ ech ...

Motion of the atoms

I recently came across an interesting effect on the IconArchive website, but I am unsure how to implement it. If anyone could help me understand the concept with a small example, that would be greatly appreciated. You can see the effect in action by visi ...

Ways to troubleshoot and verify values in PHP that are sent through AJAX

In my jQuery function, I am using AJAX to send values to a PHP file: $.ajax({ //make ajax request to cart_process.php url: "cart_process.php", type: "POST", dataType: "json", //expect json value from server data: { quantity: iqty, ...

How can I use JavaScript or CSS to identify the specific line on which certain words appear in the client's browser?

Imagine I have the following HTML structure: <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco labor ...

Comparing XDomainRequest and XMLHTTPRequest - which one to choose

Our team is currently developing an application utilizing PixiJS that integrates a dynamic json loader. The .json files are loaded using the following logic: if(window.XDomainRequest) { this.ajaxRequest = new window.XDomainRequest(); } else if (windo ...