How to add a class to an HTML element, through JavaScript. In my case, I need to add a class in the h1 element below

2

I need to add a class in element H1

  var div = document.createElement("div");
  var h1 = document.createElement("h1");
  var p = document.createElement("p");
  h1.textContent = "Me Ajuda";
  p.textContent = "Preciso adicionar uma classe";
  div.appendChild(h1);
  div.appendChild(p);
  console.log(div);
    
asked by anonymous 09.04.2018 / 02:19

2 answers

1

// Buscar elemento pai
var elemento_pai = document.body;

 var div = document.createElement("div");
  var h1 = document.createElement("h1");
  var p = document.createElement("p");
  h1.textContent = "Te ajudei! :)";
  p.textContent = "Adicionei uma classe a tag h1";
  div.appendChild(h1);
  div.appendChild(p);
  
  h1.classList.add("classH1");
  
  elemento_pai.appendChild(div);
  
.classH1
{
color:red;
}
<body></body>

classList

  

To add one or more classes to an HTML element, simply select it and call the classList.add method, passing a String as an argument. It's interesting to note that we can add multiple classes at once. To do this, enter the names of the classes you want to add separated by a comma. Example: h1.classList.add( 'classH1', 'class2', 'class3' );

// Buscar elemento pai
var elemento_pai = document.body;

 var div = document.createElement("div");
  var h1 = document.createElement("h1");
  var p = document.createElement("p");
  h1.textContent = "Te ajudei! :)";
  p.textContent = "Adicionei várias classes a tag h1";
  div.appendChild(h1);
  div.appendChild(p);
  
  h1.classList.add( 'classH1', 'class2', 'class3' )
  
  elemento_pai.appendChild(div);
  
.classH1
{
color:red;
}
.class2
{
font-size:12px;
}
.class3
{
letter-spacing : 6px;
}
<body></body>

For something more detailed (compatibility) - Can I use

    
09.04.2018 / 04:21
0

Edited

Just replace "your-class" with your class name. See the example below:

var div = document.createElement("div");
  var h1 = document.createElement("h1");
  var p = document.createElement("p");
  h1.classList.add("sua-class");
  h1.textContent = "Me Ajuda";
  p.textContent = "Preciso adicionar uma classe";
  div.appendChild(h1);
  div.appendChild(p);
  console.log(div);

Explaining the use of classList:

The classList property returns the name (s) of an element's class, such as a DOMTokenList object.

This property is useful for adding, removing, and switching CSS classes within an element.

The classList property is read-only, however, you can modify it using the add () and remove () methods.

Feedback: w3schools

    
09.04.2018 / 02:26