0
I created a function that when I click on a <div>
, she creates another <div>
with the attributes of class
and id
. In that same function I created a loop for
to be able to add id
dynamically.
I want every <div>
created, the number at the end of the id
be increased, for example:
#div-1, #div-2, #div-3...
Only this isn’t happening because he just repeats the same id
. Can someone help me adjust my function in a correct way?
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>tetes</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<link rel="stylesheet" href="css/estilo.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<div class="geral mt-4 ml-4" onclick="dispararLoop()">Clica aqui</div>
</div>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="js/script.js"></script>
</html>
JS
function dispararLoop(){
for(i = 1; i < 2; i++){
let criarDiv = document.createElement('div')
let pegarCol = document.querySelector('.col')
let id = document.createAttribute('id')
id.value = 'div-' + (i * 5)
criarDiv.setAttributeNode(id)
pegarCol.appendChild(criarDiv)
criarDiv.className = "d1"
let criarParagrafo = document.createElement('p')
criarDiv.appendChild(criarParagrafo)
function Pessoa(nome, idade, sexo, profissao){
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
this.profissao = profissao;
}
let fernando = new Pessoa("Fernando", "28", "Masculino", "Dev")
criarParagrafo.innerHTML = fernando.nome + " " + fernando.idade + " " + fernando.sexo + " " + fernando.profissao
}
}
'Cause you need Ids?
– Sergio
It’s more of a case of studies anyway, in case you need to elaborate something of the type in the future.
– Fernando Pinhel