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

135
Vistas
Inject css inline into elements using js

For example, my html code is as follows:

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>add style inline in js</title>
  <link rel="stylesheet" href="css/styles.css">
</head>

<body>
  <div class="one">
     <div class="two">
        <a href="#">link</a>
     </div>
  </div>

  <script src="js/my-scripts.js"></script>
</body>
</html>

I want to select elements and style them in my-scripts.js file like css:

.one .two a:hover{color:red;}

I have a sample jquery code:

function injectStyles(rule) {
  var div = $("<div />", {
    html: '&shy;<style>' + rule + '</style>'
  }).appendTo("body");    
}

$("button").on("click", function() {
  injectStyles('a:hover { color: red; }');
});

https://css-tricks.com/snippets/javascript/inject-new-css-rules/

but I want to do this without using jquery and without using the button. (Apply styles after loading script file)

I want to define my css code in js and define each one separately as "inline" for each element.

Thanks to the professors

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could create a template class in your css file like this

.colorOnHover a:hover {
  color: red;
}

And then you can use document.querySelector to get the element and add the colorOnHover to the classList of that element.

// your js file
const element = document.querySelector(''); // pass in the ID or the class of the element you want to add the changes to
(function() {
    element.classList.add('colorOnHover');
})();
// this will add `colorOnHover` class to the classList and apply the css defined to the class in your css file.

Make sure to link the javascript & css file (if any) using <script src = "pathHere" defer></script> and <link rel = 'stylesheet' href = "pathHere>" respectively

update : since the op didn't want to use querySelector

You could use document.createElement('style') and append it to the html file, it would be similar to manually inserting a tag

(function() {
    const styleEl = document.createElement('style');
    styleEl.textContent = '.one .two a:hover{color:red;}';
    document.head.append(styleEl);
    console.log('added new style tag');
})();
about 4 years ago · Juan Pablo Isaza Denunciar

0

This how to inject your CSS to to <style> tag :
JS & jQuery code :

function injectStyles(rule) {
  $("style").append(rule);
}

$("button").on("click", function() {
  injectStyles('.one .two a:hover{color:red;}');
});

HTML code :

<html lang="en">
<head>
  <meta charset="utf-8">
  <title>add style inline in js</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <link rel="stylesheet" href="css/styles.css">
</head>

<body>
  <div class="one">
     <div class="two">
        <a href="#">link</a><br>
       <button type="button">Make the link hover Red</button>
     </div>
  </div>

  <script src="js/my-scripts.js"></script>
</body>
</html>
about 4 years ago · Juan Pablo Isaza Denunciar
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