I can't figure out how to make these into buttons using the array:
var widgetButtons = ["Zoom In", "Zoom Out", "Pan", "Search"]
Any help would be appreciated. This is my code I am attempting to use
<body>
<div id="demo"></div>
<script>
var widgetButtons = ["Zoom In", "Zoom Out", "Pan",
"Search"];
</script>
</body>
</html>
CodePudding user response:
Here is another way to do it, using forEach()
.
IDs cannot contain spaces, so we remove the space from the item's name/text before setting the id.
const widgetButtons = ["Zoom In", "Zoom Out", "Pan", "Search"]
const demo = document.getElementById('demo');
widgetButtons.forEach( (item, idx) => {
const btn = document.createElement('button');
btn.id = item.replace(' ', '');
btn.innerText = item;
demo.appendChild(btn);
});
<html>
<body>
<div id="demo"></div>
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
In your HTML: <div id="new">
In your JS / script:
var widgetButtons = ["Zoom In", "Zoom Out", "Pan",
"Search"];
var element = document.getElementById("new");
for (const widgetButtonsKey of widgetButtons) {
var x = document.createElement("BUTTON");
x.innerText = widgetButtonsKey
console.log(x);
element.appendChild(x);
}
CodePudding user response:
Here's another approach.
var widgetButtons = ["Zoom In", "Zoom Out", "Pan", "Search"];
document.getElementById('demo').innerHTML = widgetButtons.map(text=>{
return `<button>${text}</button>`;
}).join(' ');
<div id=demo></div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
const demo = document.getElementById("demo");
var widgetButtons = ["Zoom In", "Zoom Out", "Pan",
"Search"];
//Loop through the array
for (let index = 0; index < widgetButtons.length; index )
{
//Create button element using create element
const button = document.createElement("button");
//This adds button value (title of the button)
button.innerHTML = widgetButtons[index];
//Add style to increase margin
button.style.margin = "10px";
//Append the buttons created to the body
demo.appendChild(button);
}