I want to dynamically style all elements of a given selector in my DOM. I see more or less two ways about it. For the example below I'll use a p
element and it's text-align
attribute but I'm more interested in the pros and cons of the two possible ways of doing this than I am in specifically text-aligning paragraphs.
1. Inline (per element) Styles
var nodes = document.getElementsByTagName('p');
Array.prototype.forEach.call (nodes, function (node) {
node.style.textAlign = "center";
});
2. Stylesheet
var sheet = (function() {
// Create the <style> tag
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
sheet.insertRule("p { text-align: center; }");
Typically I would go the route of inline styles, as it seems simpler and it ensures the style change would override the existing style sheets. But it occurs to me that for one: sometimes not overriding the style sheets might be preferable, and for two: it might be more performant to modify one style
element than an unknown quantity of p
elements. But that's just my assumption.
Performance wise, would there ever be a situation where applying inline styles to each individual element would be better than creating a style sheet? Assuming the answer might be dependent on how many elements I am styling, at one point does creating a style sheet become more efficient?
EDIT: To clarify why I'm asking the question, I'll explain a little about why I'm asking: I've recently turned a handful of JS hacks I've often copy-pasted and adapted between projects into a set of reusable CommonJS modules. They do things like setting all elements of a given selector the same height or width as the tallest or widest of the set in situations where the measure of the tallest or widest might be subject to change on a window resize or other triggers.
Here is a blog post about it: http://davejtoews.com/blog/post/javascript-layout-hacks
Here are the GitHub repos for the modules:
At this point, all these modules use inline styles, but I am thinking of switching them to stylesheets. I couldn't find a good answer about the pros and cons of either approach so I posted the question here.
@media
queries inline? Or are you going to do whatCSS
is doing out of the box viajavaScript
? Do you really think it's going to be faster?body.p_are_centered p { text-align: center }
js :document.body.classList.add('p_are_centered')
. Don't mess with the DOM when you don't need to. (Of course you can replacebody
with any parent node)