Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

110
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda