I'm trying to specify name=""
when using document.createElement
but isn't working.
Here is the code =>
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>
How can I fix that without using id
? Thanks
CodePudding user response:
<p>
don't have name
attributes. Try data-name
instead:
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>
CodePudding user response:
You have to use 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>