Create a ruleIndexTracker
Array which will serve as a key, translating the original index of the inserted rule to that rule's current index.
eg.
var ruleIndexTracker = [
0,
1,
2,
3,
4
];
Every time you add a new rule to the style.sheet
, add a value
to ruleIndexTracker
.
var nextIndex = (ruleIndexTracker[(ruleIndexTracker.length - 1)] + 1);
ruleIndexTracker.push(nextIndex);
So if you add a sixth and a seventh rule, you will get:
var ruleIndexTracker = [
0,
1,
2,
3,
4,
5,
6
];
You can see that you will always have an array with exactly the same number of entries as rules you have added to style.sheet
(regardless of whether those rules are still present or whether they have been subsequently deleted).
If you want to remove a rule, run the following function:
function deleteRule(originalIndex) {
ruleIndexTracker[originalIndex] = -1;
for (let i = (originalIndex + 1); i < ruleIndexTracker.length; i++) {
ruleIndexTracker[i] = (ruleIndexTracker[i] - 1);
}
}
If you now wish to remove the fourth rule you added (which always corresponds to ruleIndexTracker[3]
then running the function deleteRule(3)
above will result in the following:
var ruleIndexTracker = [
0,
1,
2,
-1,
3,
4,
5
];
Every time you need to delete a rule from the style.sheet
, you will always be able to find that rule using the following:
ruleIndexTracker[originalIndex]
This will always reveal the current index of that rule in style.sheet
.