I want to create several html elements using javascript. I have a working version but the code repeats itself, I would like to collapse it into a for loop.
Here the code to reduce:
function editerPage() {
var boutonTitre = document.createElement('button');
boutonTitre.id = 'titre';
boutonTitre.innerHTML = 'Titre de l\'onglet de la page';
boutonTitre.setAttribute('onclick', 'titre()');
var boutonH1 = document.createElement('button');
boutonH1.id = 'h1';
boutonH1.innerHTML = 'Titre h1 de la page';
boutonH1.setAttribute('onclick', 'h1()');
var boutonP = document.createElement('button');
boutonP.innerHTML = 'Paragraphe de la page';
boutonP.id = 'p';
boutonP.setAttribute('onclick', 'p()');
var inputCouleurH1 = document.createElement('input');
inputCouleurH1.innerHTML = 'Changer la couleur du titre h1';
inputCouleurH1.id = 'input';
inputCouleurH1.setAttribute('onclick', 'couleurH1()');
inputCouleurH1.setAttribute('type', 'color');
document.body.appendChild(boutonTitre);
document.body.appendChild(boutonH1);
document.body.appendChild(boutonP);
document.body.appendChild(inputCouleurH1);
}
And Here i have try to reduce it but its doesent work:
var bouton = ['title', 'h1', 'p', 'input']
function editerPage() {
for ( i = 0; i >= bouton.length; i++ ) {
bouton[i] = document.createElement('button');
bouton[i].innerHTML = 'Création du ' + bouton[i];
bouton[i].id = '"' + bouton[i] + '"';
bouton[i].setAttribute('onclick', '"' + bouton[i] + '"');
document.body.appendChild(bouton[i]);
}
}
Someone can help me please ?
setAttribute("onclick", "p()")(the former code) andsetAttribute("onclick", "p")(the latter code). Also note that you are replacing each array element with the created element, so you cannot runediterPage()twice.boutonwith elements by usingbouton[i] = document.createElement('button');. Just use a local variable likevar button = document.createElement('button');, and replacebouton[i]to the left of an equals sign or dot.withbutton... and make itdocument.body.appendChild(button);then you can run it as many times as you'd like, if you remove the part setting the ID, since those have to be unique.