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>