Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

109
Views
How can I append a 'link' tag in 'head' using JavaScript?

I want to make a feature for my website where the user can select the way the style will show up via a form.

I linked the form's elements to a JS file, but it doesn't work at all.

Here is the HTML code:

    <form>
        <label for="theme-selector">Select your theme:</label>
        <select name="theme-selector" id="theme-selector">
            <option value="auto">Automatic (default)</option>
            <option value="light">Light</option>
            <option value="dark">Dark</option>
        </select>
        <button id="apply-theme">Apply</button>
    </form>

This is how I linked it to the script:

    let theme = document.getElementById('theme-selector').value;
    let applyBtn = document.getElementById('apply-theme');
    
    let time = new Date();
    time = time.getHours();
    
    applyBtn.addEventListener('click', () => {
    
        let node = document.createElement('link');
        node.rel = 'stylesheet';
    
        if(theme == 'auto') {
            if(time >= 10 && time <= 19) {
                // daytime theme
                node.href = 'style/light.css';
            }
            else {
                // nighttime theme
                node.href = 'style/dark.css';
            }
        }
        else {
            // chosen theme
            node.href = `style/${theme}.css`;
        }
    
        document.head.appendChild(node);
    });

The "auto" thing is made so it will set different themes depending on what time is it.

I don't understand why it doesn't work. I am very new in JavaScript so please be kind, thanks!

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!