1

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?

10
  • 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. Commented 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? Commented Nov 12, 2020 at 13:18
  • 1
    @Rounin <style> Commented Nov 13, 2020 at 8:45
  • Hah! Thank you, @netizen. My fingers were typing, but my brain was switched off. :-) Commented Nov 13, 2020 at 9:11
  • 1
    yes @Rounin yours solution works too but I needed a more general solution. thank you. Commented Nov 13, 2020 at 13:34

2 Answers 2

3

. 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>        
Sign up to request clarification or add additional context in comments.

1 Comment

Instead of constructing an array to get first element with getElementsByTagName, just access first <head> directly as a standard document property: document.head
0

Put your CSS file under the public folder, if you are using a handlebar.

Public folder

If you are not depending on any handlebars, save the file separately and then call it using a <link> tag.

<link rel="stylesheet" href="styles.css"></link>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.