For example, the first time I clicked, a red block was added, the second time I clicked on the same link, a blue block was added, and so on?

    1 answer 1

    jQuery:

    var color = [ "red", "green", "blue" ]; $(function() { var add_block = $("#add_block"); add_block.click(function() { $("#blocks").append("<div style=\"background: " + color[$("#blocks div").length] + " \">test</div>"); }); }); 
     <script src="//code.jquery.com/jquery.min.js"></script> <button id="add_block">Добавить блок</button> <div id="blocks"></div> 

    Javascript:

     var colors = [ "red", "green", "blue" ]; window.onload = function() { var add_block = document.getElementById("add_block"); var blocks = document.getElementById("blocks"); add_block.addEventListener("click", function() { var div = document.createElement("div"); div.style.background = colors[blocks.getElementsByTagName("div").length]; div.innerHTML = "test"; blocks.appendChild(div); }, false); } 
     <button id="add_block">Добавить блок</button> <div id="blocks"></div> 

    PS We create an array with colors and when we click the Добавить блок button, we add a div element to <div id="blocks"></div> . Color is defined as:

    We have an array of color:

     // colors[0] => red // colors[1] => green 

    Instead of zero or one, as shown above (and in any other case there will be any), we substitute the number of already created blocks. That is, if 1 element is created, then by the condition of our code the next color for the div-блока will be green , then blue and so on.