javascriptfunctionswitch-statementcounterheading

After click on button show in the *div* the text as heading 1 <h1>, second click <h2> etc. After 6, is next text (7th) as <h1> again


I want to make a website with text box, button using switch -case and div with id 'divResult'. If you click on button it shows text from text box as heading 1 <h1>, after second click as <h2> etc. After 6, is next text (7th) as <h1> again. It works correct only last step (text in h1-h6) doesn't work.

<!Doctype HTML>
<html>
<head>
  <meta charset="utf-8">
  <title>7-3</title>
  <script >
    
var index = 1;
var countClicks = 0;

window.onload = function () {
  document.getElementById('btnKnop').onclick = function () {

    var newElement = document.createElement('div');
    newElement.id = 'div' + index++;
    
    var node = document.getElementById('txtElement').value;
    var newNode = document.createTextNode(node);
    
    newElement.appendChild(newNode);

				
    console.log(newElement);
    document.getElementById('divResult').appendChild(newElement);


  countClicks++;
  switch (countClicks) {
    case 1: {
      console.log('heading text 1');
      break;
    }
    case 2:{
      console.log('heading text 2');
      break;
    }
    case 3:{
      console.log('head text 3');
      break;
    }
    case 4:{
      console.log('heading text 4');
      break;
    }
    case 5:{
      console.log('heading text 5');
      break;
    }
    case 6:{
      console.log('heading text 6');
      countClicks = 0;
      break;
      }
    }
       
  };
};  
  </script>
</head>
<body>
  <input type="text" id="txtElement">
  <button id="btnKnop">Add</button>
  <div id="divResult"></div>
  

</body>


</html>


Solution

  • Here is an example using your HTML, and little JS, you don't need a switch statement for that

    var txtInput = document.querySelector("#txtElement"),
      resultElement = document.querySelector("#divResult"),
      ind = 0;
    
    document.querySelector("#btnKnop").onclick = function() {
      ind = ind++ === 6 ? 1 : ind;
      resultElement.innerHTML += `<h${ind}>${txtInput.value}</h${ind}>`;
    }
    <input type="text" id="txtElement">
    <button id="btnKnop">Add</button>
    <div id="divResult"></div>

    Since you need to use a switch statement for your execise it can be like this:

    var txtInput = document.querySelector("#txtElement"),
      resultElement = document.querySelector("#divResult"),
      countClicks = 1;
    
    document.querySelector("#btnKnop").onclick = function() {
      var h = "";
      switch(countClicks++) {
        case 1: h = "h1"; break;
        case 2: h = "h2"; break;
        case 3: h = "h3"; break;
        case 4: h = "h4"; break;
        case 5: h = "h5"; break;
        case 6: h = "h6"; countClicks = 1; 
      }
      resultElement.innerHTML += `<${h}>${txtInput.value}</${h}>`;
    }
    <input type="text" id="txtElement">
    <button id="btnKnop">Add</button>
    <div id="divResult"></div>