How do I create elements and add attributes with pure javascript?

1

I do not 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>
    
asked by anonymous 01.04.2018 / 22:38

2 answers

1

The correct way to put attributes in an element with pure Javascript is setAttribute . In this case you will add the attribute if it does not exist or just 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, however, it is more advisable to use classList , because it allows you to easily add and / or remove multiple classes.

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

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

Among others. So it would be more advisable in the example you had to use classList with add :

x.classList.add("bloco");

See it 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>
    
01.04.2018 / 23:05
0

I think your approach is complicated for something simpler. You can assign attributes in this simpler 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>
    
01.04.2018 / 23:16