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>