Approach:
- Use document.getElementsByTagName() method to get HTML head element.
- Create new link element using createElement('link') method.
- Initialize the attributes of link element.
- Append link element to the head.
Example 1: This example uses JavaScript to add CSS file in HTML document.
- Create CSS file using name style.css:
.GFG { color:green; }
- Use JavaScript to add CSS file:
<!DOCTYPE html> <html> <head> <title> Load CSS file using JavaScript </title> <script> // Get HTML head element var head = document.getElementsByTagName('HEAD')[0]; // Create new link Element var link = document.createElement('link'); // set the attributes for link element link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'style.css'; // Append link element to HTML head head.appendChild(link); </script> </head> <body> <h2 class="GFG">GeeksForGeeks</h2> </body> </html>
0 Comments