I’ve seen two methods of adding CSS to the head of an HTML page from the body using JavaScript and jQuery, which is preferred?
$('head').append("<style type='text/css'> my CSS <\/script>");
or
var styleElement = document.createElement('style');
var styleText = 'my CSS';
var headElements = document.getElementsByTagName('head');
styleElement.type = 'text/css';
if (headElements.length == 1) {
headElements[0].appendChild(styleElement);
} else if (document.head) {
document.head.appendChild(styleElement);
}
if (styleElement.styleSheet) { // IE
styleElement.styleSheet.cssText = styleText;
} else { // Other browsers
var textNode = document.createTextNode(styleText);
styleElement.appendChild(textNode);
}
Obviously the first is a lot shorter, but is it less accepted?
It’s a question of readability vs performance, I think.
People would argue (and they’d be normally correct) that doing stuff the raw Javascript way is faster than if done with jQuery — and why wouldn’t that be? jQuery abstracts the raw Javascript calls from what you’re doing to present nice syntax and convenience. That means that you’ll incur additional overhead when using jQuery, as your commands will zig and zag through it’s innards until it gets to the part where it “translates” what you’re doing into raw Javascript code.
But then again, writing raw Javascript code can not only be tedious from time to time (just look at all that code!), but also susceptible to cross-browser problems (which jQuery attempts to normalize), and can be harder to read to the uninitiated. Is the performance benefit really worth it?
It’s a matter of where and what you’re trying to do, honestly. Here, I’d say that the benefits of going raw Javascript is negligible. Hit that up in jQuery.