Reputation: 25
Is it possible to modify css :nth-child property dynamically using pure js?
.tile:nth-child(10n + 1) {
clear: both;
}
For example sth like this add using js
Upvotes: 1
Views: 1801
Reputation: 327
As Pariket Thakur said, you can use document.querySelector("your selectors")
.
If you want to select multiple elements, use document.querySelectorAll("your selectors")
.
For example:
var elements = document.querySelectorAll("p:nth-child(2n+1)");
for (i = 0; i < elements.length; i++) {
elements[i].style.color = "red";
}
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
<p>Paragraph 5</p>
See W3Schools for further information.
Upvotes: 2
Reputation: 23406
It's not clear, whether you want to edit the selector or the property of the rule. The code snippet below can do both.
class Css {
addRule(selector, properties) {
const rule = this.styleSheet.insertRule(selector + ' ' + properties);
this[selector] = this.styleSheet.rules[rule];
return this[selector];
}
createStyleSheet() {
const styleElement = document.head.appendChild(document.createElement('style'));
this.styleSheet = document.styleSheets[document.styleSheets.length - 1];
return this;
}
}
const css = new Css().createStyleSheet(),
pNth = css.addRule('p:nth-child(1)', '{color: red; position: relative;}');
// A use-case showing how to use the stored rule
setInterval(_ => {
const index = Math.floor(Math.random() * 3) + 1;
// Change selector via selectorText property
css['p:nth-child(1)'].selectorText = `p:nth-child(${index})`;
// Edit/add a property via style property
pNth.style.left = `${index}em`;
}, 500);
<div>
<p>Text</p>
<p>Chapter</p>
<p>Paragraph</p>
</div>
When a document contains multiple large stylesheets, it's hard and time-consuming to find a correct rule to edit. Also, most of the browsers don't allow you to modify cross-domain stylesheets. These issues can be resolved by creating an inline style
element to the head section of the document, and add the new rules to that stylesheet. It's notable, that inline stylesheet rules have a higher specificity, hence the added rules might break the planned cascading, thought it also makes sure, that the edited rules are also applied to the document.
An instance of Css
class contains two methods. createStyleSheet
creates a new style element and appends it to the head, and returns the instance itself. addRule
adds new rules to the newly-created stylesheet according to the arguments passed to it. The method also stores references to the rules it creates to a property named by the passed selector. Finally the method returns a reference to the newly-created rule.
When you need to add a rule, you call addRule
method. It's not mandatory to store the return value to a variable, you can always refer to the rule using css
object and the original selector of the rule to change the selector or the properties of the rule.
Upvotes: 1