Tengo este código html que crea un button y establece algunos atributos para él.
<button type="button" class="btn dropdown-toggle text-left font-weight-bolder" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style=" width: fit-content; border-radius: 18px !important; border-color: black; border-width: 4px; font-size: 20px; padding: 0.2rem 0.3rem !important; margin-top: 5px !important;" > <i class="mr-3"></i> Add Question </button>Aunque debido a que estoy creando una aplicación dinámica, necesito crear este elemento en JavaScript para poder pasarlo como argumento en las funciones.
Quiero ser capaz de hacer algo como esto:
var addQuestionButton = document.createElement("button");Y luego quiero con algo de código agregar estos atributos que tenía antes. Pensé algo como:
addQuestionButton.type = "button"; addQuestionButton.className ="btn dropdown-toggle text-left font-weight-bolder"; addQuestionButton.toggle = "dropdown"; . . .Pero parece que no funciona. ¿Hay alguna manera de que pueda hacer esto?
Puede agregar atributos mediante la función setAttribute .
element.setAttribute(attributeName, attributeValue) var addQuestionButton = document.createElement("button"); var i = document.createElement("i"); i.className = 'mr-3' addQuestionButton.className = 'btn dropdown-toggle text-left font-weight-bolder' addQuestionButton.setAttribute('type', 'button') addQuestionButton.setAttribute('aria-haspopup', 'true') addQuestionButton.setAttribute('data-toggle', 'dropdown') addQuestionButton.setAttribute('style', `width: fit-content; border-radius: 18px !important; border-color: black; border-width: 4px; font-size: 20px; padding: 0.2rem 0.3rem !important; margin-top: 5px !important;`) addQuestionButton.appendChild(i) addQuestionButton.appendChild(document.createTextNode('Add Question')) document.body.appendChild(addQuestionButton)Puedes hacer esto
//get parrent let e = document.getElementById("div") //create button let button = document.createElement("button") //add button to parrent e.appendChild(button) //add the attribute e.setAttribute("type", "button" ) e.setAttribute("class", "btn dropdown-toggle text-left font-weight-bolder" ) e.setAttribute("toggle ", "dropdown" ) . . . let i= document.createElement("i") button.appendChild(i) i.textContent = yourText