Add attributes to html element through JavaScript

I have this html code that creates a button and sets some attributes for it.

      <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>

Although because I am creating a dynamic application I need to be creating this element in JavaScript so I can pass it as an argument in functions.

I want to be able to do something like this:

var addQuestionButton = document.createElement("button");

And then I want with some code to add these attributes that it had before. I thought something like:

addQuestionButton.type = "button";
addQuestionButton.className ="btn dropdown-toggle text-left font-weight-bolder";
addQuestionButton.toggle = "dropdown";
.
.
.

But it seems not to work. Is there any way that I can do this?

>Solution :

You can add attributes by the setAttribute function.

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)

Leave a Reply