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.