Home >Web Front-end >JS Tutorial >How to introduce css in js
How to introduce css into js: 1. Use the "document.write" method to output the link tag that introduces css; 2. Use the createElement method to dynamically create a link tag to introduce css.
The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.
js imports css files
1. Use the document.write method to output the link tag that imports css
Add the following example code at the top of the calling file
<script> document.write('<link rel="stylesheet" href="main.css">'); </script>
2. Use the createElement method to dynamically create link tags to introduce css
Put the following code into the Body
<script> new_element = document.createElement('link'); new_element.setAttribute('rel', 'stylesheet'); new_element.setAttribute('href', 'main.css'); document.body.appendChild(new_element); </script>
Let’s analyze the key lines of code :
First we use document.createElement('link') to generate a link tag;
Then set its rel attribute to stylesheet and href to main.css;
Finally, this tag is dynamically added to the body.
【Recommended learning: javascript advanced tutorial】
The above is the detailed content of How to introduce css in js. For more information, please follow other related articles on the PHP Chinese website!