通过JavaScript向HTML元素添加属性

3
我有这段创建一个按钮并设置一些属性的 html 代码。
      <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>

尽管我正在创建一个动态应用程序,但由于需要将其作为参数传递到函数中,因此我需要在JavaScript中创建此元素。
我希望能够像这样做:
var addQuestionButton = document.createElement("button");

接下来,我希望你能够使用一些代码来添加这些之前已经存在的属性。我考虑了类似于:

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

但似乎它不起作用,有没有什么方法可以做到这一点?


1
你可以使用 element.setAttribute(attributeName, attributeValue) 函数。 - Mina
2个回答

1

您可以使用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)


0
你可以这样做。
//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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接