When I used just HTML and CSS files for my website the CSS effects got applied normally. But when I tried to run my website using node.js all the CSS effects got removed. How can I incorporate my CSS file into my app.js file?
-
You should try googling your question before asking it on SO, and seeing if anything works for you. Also, if nothing works, we need to see what you've tried. Your code along with an explanation, if necessary.VirxEC– VirxEC2020-11-12 12:42:51 +00:00Commented Nov 12, 2020 at 12:42
-
Could you please clarify if this is about client-side or server-side JavaScript? Are you using a framework like Express?over-engineer– over-engineer2020-11-12 13:18:37 +00:00Commented Nov 12, 2020 at 13:18
-
1@Rounin <style>netizen– netizen2020-11-13 08:45:46 +00:00Commented Nov 13, 2020 at 8:45
-
Hah! Thank you, @netizen. My fingers were typing, but my brain was switched off. :-)Rounin– Rounin2020-11-13 09:11:38 +00:00Commented Nov 13, 2020 at 9:11
-
1yes @Rounin yours solution works too but I needed a more general solution. thank you.Shubham_s– Shubham_s2020-11-13 13:34:40 +00:00Commented Nov 13, 2020 at 13:34
|
Show 5 more comments
2 Answers
. 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:
Create CSS file using name style.css:
.Setcolor {
color:blue;
}
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="Setcolor">TheColoris</h2>
</body>
</html>
1 Comment
netizen
Instead of constructing an array to get first element with getElementsByTagName, just access first <head> directly as a standard document property:
document.head