How to create elements and add attributes with pure javascript?

Asked

Viewed 484 times

2

I don’t know why my test is going wrong.

var t = document.querySelector("#t");

var x = document.createElement('div');

var y = document.createAttribute("id");
y.value = "azul";
var b = document.createAttribute("class");
y.value = "bloco";

x.attributes.setNamedItem(y);
x.attributes.setNamedItem(b);

t.appendChild(x);
#t{
  width: 300px;
  background: red;
 height: 300px; 
}
.bloco{
  width: 30px;
  height: 30px;
  display: block; 
}
#verde{
   background: green;
}
#azul{
  background: blue;
}
<div id="t">
  <div class="bloco" id="verde"></div>
  
  
</div>

2 answers

3


The correct way to place attributes on an element with pure Javascript is setAttribute. In this case you will add the attribute if it does not exist or only update its value if it already exists.

In your example it would look like this:

var t = document.querySelector("#t");
var x = document.createElement('div');

x.setAttribute("id", "azul"); //adicionar o atributo id com o valor azul
x.setAttribute("class", "bloco"); //adicionar o atributo class com o valor bloco

t.appendChild(x);
#t{
  width: 300px;
  background: red;
 height: 300px; 
}
.bloco{
  width: 30px;
  height: 30px;
  display: block; 
}
#verde{
   background: green;
}
#azul{
  background: blue;
}
<div id="t">
  <div class="bloco" id="verde"></div>
</div>

To manipulate classes is however more advisable to use classList, as it allows you to easily add and/or remove multiple classes.

In this case you have at your disposal various methods such as:

  • add - to add a new class
  • remove - to remove an existing class
  • contains - to know if a certain class exists

Among others. Soon it would be more advised in the example it had would be to use the classList with add:

x.classList.add("bloco");

See working:

var t = document.querySelector("#t");
var x = document.createElement('div');

x.setAttribute("id", "azul"); //adicionar o atributo id com o valor azul
x.classList.add("bloco"); //a classe bloco

t.appendChild(x);
#t{
  width: 300px;
  background: red;
 height: 300px; 
}
.bloco{
  width: 30px;
  height: 30px;
  display: block; 
}
#verde{
   background: green;
}
#azul{
  background: blue;
}
<div id="t">
  <div class="bloco" id="verde"></div>
</div>

0

I think your approach is complicated for something simpler. You can assign attributes this simple way:

var t = document.querySelector("#t");
var x = document.createElement('div');
x.id = "azul"; // adiciono o id
x.className = "bloco"; // adiciono a classe

t.appendChild(x);
#t{
  width: 300px;
  background: red;
 height: 300px; 
}
.bloco{
  width: 30px;
  height: 30px;
  display: block; 
}
#verde{
   background: green;
}
#azul{
  background: blue;
}
<div id="t">
   <div class="bloco" id="verde"></div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.