Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

111
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda