0

I am following this thread which shows how to generate DOM elements dynamically. Suppose I have this snippet that generate a series of buttons:

for(var i = 0; i < result.length;i++){
      var menuCatButton = document.createElement("button");
      menuCatButton.id = "menu-mgt-button-"+result[i];
      menuMgtCategoryButtons.appendChild(menuCatButton);
}

How do I apply this set of style to all of the newly created buttons?

.new-button {
  background-color: #4CAF50;
  border: 1px solid;
  color: white;
  text-decoration: none;
  display: inline-block;
  font-size: 15px;
  margin: 4px 20px;
  cursor: pointer;
  width: 120px;
  height:50px;
  white-space: normal;
}

.new-button:hover {
  box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
Tristan Tran
  • 1,351
  • 1
  • 10
  • 36

3 Answers3

3

You can add the class the element using classList.add().

Demo:

var result = [1,2];
var menuMgtCategoryButtons = document.getElementById('menuMgtCategoryButtons');
for(var i = 0; i < result.length;i++){
  var menuCatButton = document.createElement("button");
  menuCatButton.id = "menu-mgt-button-"+result[i];
  menuCatButton.textContent = "Button "+result[i]; // add the text to the button
  menuCatButton.classList.add('new-button'); // add the class to the button
  menuMgtCategoryButtons.appendChild(menuCatButton);
}
.new-button {
  background-color: #4CAF50;
  border: 1px solid;
  color: white;
  text-decoration: none;
  display: inline-block;
  font-size: 15px;
  margin: 4px 20px;
  cursor: pointer;
  width: 120px;
  height:50px;
  white-space: normal;
}

.new-button:hover {
  box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
<div id="menuMgtCategoryButtons"></div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
2

Add this line

menuCatButton.className="new-button"
farvilain
  • 2,552
  • 2
  • 13
  • 24
2

Just add the class to each element in the loop just after you have created the element.

menuCatButton.classList.add("new-button");
caramba
  • 21,963
  • 19
  • 86
  • 127
  • Thanks for responding first. I am going to accept @Mamun solution because it leads me to dig up more on ```createElement```. – Tristan Tran Nov 28 '20 at 08:17