document.createElement with name



我试图在使用document.createElement时指定name="",但不起作用。

这是代码=>

var element = document.createElement("p");
element.className = "hello-there";
element.innerText = "It works";
element.name = "hello-there-name";
document.getElementById("main").appendChild(element);
console.log(document.querySelector("p").getAttribute("name"));
<div id="main"></div>

如何在不使用id的情况下解决此问题?感谢

<p>没有name属性。改为尝试data-name

var element = document.createElement("p");
element.className = "hello-there";
element.innerText = "It works";
element.dataset.name = "hello-there-name";
document.getElementById("main").appendChild(element);
console.log(document.querySelector("p"));
<div id="main"></div>

您必须使用setAttribute:

var element = document.createElement("p");
element.className = "hello-there";
element.innerText = "It works";
element.setAttribute("name", "hello-there-name");
document.getElementById("main").appendChild(element);
console.log(document.querySelector("p").getAttribute("name"));
<div id="main"></div>

相关内容

最新更新