How to load CSS files using JavaScript?

Share Your Love

Here in this post, we will discuss on to load CSS files using javascript.

There are numerous ways to add CSS files inside an HTML document. Generally, JavaScript can also be used to load a CSS file in the HTML document.

These are the points or approaches we have to follow:

  • 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 files in HTML documents.

  • Create CSS file using name style.css:
.LTH {
	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="LTH">LingarajTechhub</h2>
</body>

</html>					

Join Our Community

Join our WhatsApp Group To know more about Programming Language tips, tricks and knowledge about and how to start learning any programming language.

Example 2: This example uses JavaScript to add CSS files in HTML documents.

  • Create CSS file using name style.css:
.LTH {
	font-size:24px;
	font-weight:bold;
	color:white;
	background-color:green;
	padding:10px;
	text-align:center;
}
  • Use JavaScript to add CSS file:
<!DOCTYPE html>
<html>

<head>
	<title>
		Load CSS file using JavaScript
	</title>

	<script>
	
		// 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';

		// Get HTML head element to append
		// link element to it
		document.getElementsByTagName('HEAD')[0].appendChild(link);

	</script>
</head>

<body>
	<div class="LTH">LingarajTechhub</div>
</body>

</html>					

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 411

Newsletter Updates

Enter your email address below to subscribe to our newsletter