When it comes to adding CSS to the head of an HTML page from the body using JavaScript and jQuery, I have come across two methods. One involves using jQuery to directly append the CSS to the head, while the other method involves creating a style element and adding it to the head manually. Which method 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);
}
While the first method is more concise, is it less accepted in the web development community?