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

145
Vistas
JavaScript, how to add css attribute to a newly created element?

I am trying to add my element to the unordered list. But during the creation of the element I also want to link this to an external css file which has the css property. I have referred following Stack Overflow solutions : Add CSS attributes to element with JavaScript.

let a = document.getElementsByTagName('ul')[0];

let myelement = document.createElement('li');

// tried this first 
myelement.style.border = '2px solid red';

myelement.style.backgroundColor = 'rgb(255, 125, 115)';

let mytext = document.createTextNode('Green Onions');


// second method I tried to link with the external CSS file which I actually want

myelement.setAttribute("class","myclass")


// third method I tried to link with the external CSS file which I actually want

let myattrib = document.createAttribute('class');
myattrib.value = "myclass"
myelement.setAttributeNode(myattrib)


a.appendChild(mytext)
.myclass {
    color: brown;
    text-emphasis-color:blue;
}
<html>
<head>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <h1 id="header">Last King</h1>
    <h2>Buy Groceries</h2>
    <ul>
        <li id="one" class="hot"><em>fresh</em>figs</li>
        <li id="two" class="hot">pine nuts</li>
        <li id="three" class="hot">honey</li>
        <li id="four">balsamic sugar</li>

    </ul>
    <script src="index.js">

    </script>
</body>
</html>


   

None of these methods works in adding a new element with a CSS property, although with the first method I am able to just add the text node Green Onions. I am learning JS for the first time. Can someone provide me with information on what I am doing wrong?

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

0

You are not seeing anything happening because, that li you are creating, is not being added in the DOM. Other than that all your attempts work. I kept in the code below the simplest one.

let ul = document.querySelector("ul"); // line I changed

let myelement = document.createElement("li");
let mytext = document.createTextNode("Green Onions");
myelement.appendChild(mytext); // line I added
myelement.setAttribute("class", "myclass");

ul.appendChild(myelement); // line I added
.myclass {
  color: brown;
  text-emphasis-color: blue;
}
<h1 id="header">Last King</h1>
<h2>Buy Groceries</h2>
<ul>
  <li id="one" class="hot"><em>fresh</em>figs</li>
  <li id="two" class="hot">pine nuts</li>
  <li id="three" class="hot">honey</li>
  <li id="four">balsamic sugar</li>
</ul>

about 4 years ago · Juan Pablo Isaza Denunciar

0

There are two properties you could use, classList and className. As I understand it, you want to achieve this:

<li style="border:...;background-color:..." class="myclass">

You already created your element and added the styles but now you don't know how to add the css class myclass, right?

let myelement = document.createElement('li');

// method a
myelement.className = 'myclass';

// method b
myelement.classList.add('myclass');

I would always go for classList. With all its methods I find it much more elegant than className.

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