I tried to add HTML code after clicking a button.
Here is the thing; you input the tab's name then click the button linked to the addTab function. Then I tried to write the code using createElement(), setAttribute() and appendChild() but nothing works.
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
function addTab() {
var tabname = entree.value;
var btn = document.createElement("BUTTON");
btn.innerHTML = tabname;
btn.setAttribute("class", "tablinks")
btn.setAttribute("onlick", "openTab(event, ${tabname})");
var tabbar = document.getElementsByClassName("tab");
document.tabbar.appendChild(btn);
var tabdiv = document.createElement("DIV");
document.body.appendChild(tabdiv);
tabdiv.setAttribute("id", tabname);
tabdiv.setAttribute("class", "tabcontent")
var tabp = document.createElement("P");
var tabptxt = document.createTextNode("Réussite.");
tabp.appendChild(tabptxt);
}
header {
padding-bottom: 10px;
}
.tab {
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
.tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
}
.tab button:hover {
background-color: #ddd;
}
.tab button.active {
background-color: #ccc;
}
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
<header>
<label>Enter tab's name : </label>
<input type="text" id="entree" minlength="4" maxlength="12" size="12">
<button onclick="addTab()">VALIDER</button>
</header>
<body>
<div class="tab">
<button class="tablinks" onclick="openTab(event, '12septembre')">12septembre</button>
<button class="tablinks" onclick="openTab(event, '7octobre')">7octobre</button>
</div>
<div id="12septembre" class="tabcontent">
<h3>12 septembre</h3>
</div>
<div id="7octobre" class="tabcontent">
<h3>7 octobre</h3>
</div>
</body>
As I'm not experimented using Js, i get lost easily!
I also wondered, is this the best way to add tabs dynamically?
Thanks for your help.

btn.setAttribute("onlick", "openTab(event, ${tabname})");<-- wrong, because the sting will be unquouted and you really should be using addEventListener