AI Overview
To insert a <style> tag into the <head> element using JavaScript, follow these steps:
Create the <style> element: Use document.createElement() to create a new <style> element.
Add CSS rules: Set the textContent or innerHTML property of the created <style> element to the desired CSS rules.
Append to the <head>: Use document.head.appendChild() to add the newly created <style> element as a child of the <head> element.
Here is an example:
JavaScript
// 1. Create the <style> element
const styleElement = document.createElement('style');
// 2. Add CSS rules
styleElement.textContent = `
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
h1 {
color: #336699;
text-align: center;
}
p {
margin-left: 20px;
color: #555;
}
`;
// 3. Append to the <head>
document.head.appendChild(styleElement);