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?
headElement.gEBTNreturns an arraylike structure; you need to grab the first element out of the value it returns.var headElement = document.getElementsByTagName('head')[0];