0

I am trying to append some CSS and JS to my static HTML file. CSS and JS files are stored in the same folder. It sounds stupid, but I need to do that. So, CSS and JS have been appended but they are not applying to a HTML file because background should be red. The path that I created is correct because if I do inspect element on Chrome Devtools and click to appended link it opens what I need. So, there are no errors, scrip appends what I need, but I see no result.

My HTML file

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Home</title>
</head>
<body>

hello world

<script>
  const href = window.location.pathname;
  const chunkIndex = href.lastIndexOf('/');
  const path = href.slice(0, chunkIndex + 1);

  function appendScripts() {
    const script = document.createElement("script");
    script.src = path + "scripts.js";    // use this for linked script
    document.body.appendChild(script);
  }

  function appendCSS() {
    link=document.createElement('link');
    link.href= path + 'styles.css';
    link.rel='rel';
    document.getElementsByTagName('head')[0].appendChild(link);
  }

  document.addEventListener("DOMContentLoaded", function(event) {
    appendCSS();
    appendScripts();
  });
</script>

</body>
</html>

My CSS file:

body {
  background-color: red;
}
5
  • Have you checked the browser console for any errors or double checked the path of the new css file is correct and not returning a 404? Commented Nov 18, 2017 at 10:05
  • I've checked, no errors and the path that I created is correct because if I do inspect element on Chrome Devtools and click to appended link it opens what I need. Commented Nov 18, 2017 at 10:06
  • 2
    Try changing rel to stylesheet and add type with the value of text/css. Example: link.type="text/css" link.rel="stylesheet" Commented Nov 18, 2017 at 10:10
  • @NewToJS ooh, thanks so much, it works now! Commented Nov 18, 2017 at 10:12
  • You are very welcome. Not sure how I missed that from the first read but I did notice it just after you said no errors in the console and the link is correct :p Commented Nov 18, 2017 at 10:14

1 Answer 1

2

You need to fix the following line

link.rel='rel';

to

link.rel='stylesheet';
Sign up to request clarification or add additional context in comments.

3 Comments

Sure, whenever your are comfortable. :)
it's not about comfort. the system of SO doesn't give me to accept any answer so fast because i've just created a question.
ohh. Sorry my bad. New to SO :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.