By default, there are no blocks on the page. They are added by clicking the corresponding button on the page. And here, for example, I have added 5 blocks on the page. It is necessary when you click on the block to select it.

var dashboard = document.getElementById('dashboard'); var addButton = document.getElementById('addButton'); var name = document.getElementById('widgetName'); var count = document.getElementById('widgetCount'); var color = document.getElementById('widgetColor'); var widget; addButton.onclick = function() { createWidget(name.value, count.value, color.value); } function createWidget(name, count, color) { widget = document.createElement('div'); widget.className = 'widget'; var pName = document.createElement('p'); pName.innerHTML = "Name: "+name; var pCount = document.createElement('p'); pCount.innerHTML = "Count: "+count; widget.appendChild(pName); widget.appendChild(pCount); widget.style.borderColor = color; dashboard.appendChild(widget); } 

How to select a block (You can select only one block)?

  function choose(widget) { widget.style.backgroundColor = '#ccc'; } 

But the widget undefined . How to assign a widget all added blocks?

    1 answer 1

    Well, if I understood correctly, it would not be a bad decision when clicking on a block to access it using "event.target".

    That is, to have a function - click handler and change the color of the element in it. Something like this:

     function clickHandler(event) { event.target.style.backgroundColor = '#ccc'; } 

    Well, according to when creating a widget, add this function as a click handler:

     widget.onclick = chickHandler; 

    But still, I strongly advise you not to change the styles, but add the css class.