KOMPX.COM or COMPMISCELLANEA.COM   

Add an external CSS file by JavaScript

Adding an external CSS file by JavaScript:

This text turns red after the external CSS file is added...

HTML code:


<div class="example">
	<p>This text turns <b class="underline">red</b> after the external CSS file is added...</p>
</div>
<input type="button" value="Add external CSS" />

JavaScript code:


<script>
var button = document.querySelector('input[value="Add external CSS"]');
function externalStylesheet() {
	if ( !document.querySelector('link[href="stylesheet.css"]') ) {
		// Add external CSS file
		var head = document.head;
		var stylesheet = document.createElement('link');
		stylesheet.rel = "stylesheet";
		stylesheet.href = "stylesheet.css";
		head.appendChild( stylesheet );
		// Change button text
		button.value = "Remove external CSS";
	} else {
		// Remove external CSS file
		document.querySelector('link[href="stylesheet.css"]').remove();
		// Change button text
		button.value = "Add external CSS";
	}
}
button.addEventListener( 'click', externalStylesheet );
</script>

Browser support
Windows
Edge 12.0+
Firefox 61.0+
Google Chrome 4.0+
Opera 12.1+
Linux
Firefox 61.0+
Google Chrome 4.0+
Opera 12.1+
iOS
Safari 4.0+
Android
Samsung Internet 1.0+
Chrome Android 18.0+
Firefox for Android 61.0+
Opera Android 12.1+
More