Básicamente, necesito cargar botones dinámicamente en div y mostrarlos.
Este es el código que tengo hasta ahora. El problema es que necesito mostrarlo dentro de div, porque necesito mostrarlos de esta manera (como en la imagen). Probé con onload pero aparentemente no funciona con div ( <div id="from" onload="printBtn()">) cuando probé con iframe, los botones se muestran en el lugar equivocado. ¿Cómo puedo arreglarlo?
var uniqfrom = ["Tel-Aviv", "Amsterdam", "New York", "London"]; function printBtn() { for (var i = 0; i < uniqfrom.length; i++) { var btn = document.createElement("button"); var t = document.createTextNode(uniqfrom[i]); btn.appendChild(t); document.body.appendChild(btn); } } body, div { margin: 0px; padding: 0px; } #container { width: 100%; height: 500px; } #to, #controls, #from { float: left; width: 30%; height: 100% } #from { background-color: yellow; } #to { background-color: orange; } button { width: 200px; height: 50px; font-size: 20px; margin: 0 auto; background-color: blue; display: block; color: white; } h1 { text-align: center; } .sel { color: red; } <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <div id="container"> <div id="from"> </div> <div id="to"> </div> </div> </body> </html>Obtenga los DIV en los que desea colocar los botones y agregue los botones allí en lugar de document.body .
var uniqfrom = ["Tel-Aviv", "Amsterdam", "New York", "London"]; function printBtn() { let from = document.getElementById("from"); let to = document.getElementById("to"); for (var i = 0; i < uniqfrom.length; i++) { var btn = document.createElement("button"); var t = document.createTextNode(uniqfrom[i]); btn.appendChild(t); from.appendChild(btn); if (i > 0) { btn = btn.cloneNode(true); to.appendChild(btn); } } } printBtn(); body, div { margin: 0px; padding: 0px; } #container { width: 100%; height: 500px; } #to, #controls, #from { float: left; width: 30%; height: 100% } #from { background-color: yellow; } #to { background-color: orange; } button { width: 200px; height: 50px; font-size: 20px; margin: 0 auto; background-color: blue; display: block; color: white; } h1 { text-align: center; } .sel { color: red; } <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <div id="container"> <div id="from"> </div> <div id="to"> </div> </div> </body> </html>