Inserting a Tag with JavaScript</h2> <p><strong>Question:</strong></p> <p>How can you create a <style> tag and insert it into an HTML page using JavaScript? Is there a method that is more elegant and cross-browser compatible than the current solution that uses innerHTML?</p> <p><strong>Answer:</strong></p> <p>The preferred approach is to append the style element directly to the <head> of the document. This method works consistently across major browsers, including Chrome. Here's an improved solution:</p> <pre>var css = 'h1 { background: red; }', head = document.head || document.getElementsByTagName('head')[0], style = document.createElement('style'); head.appendChild(style); style.type = 'text/css'; if (style.styleSheet) { // This is required for IE8 and below. style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); }</pre> <p>This method provides the following advantages:</p> <ul> <li>It is more elegant and concise.</li> <li>It works in all major browsers, including Chrome.</li> <li>It avoids the need for an additional <br> element in front of the style tag to fix cross-browser issues.</li> </ul>