0

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

2 Answers2

3

<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>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43
2

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>
kelsny
  • 23,009
  • 3
  • 19
  • 48
  • Hello. Thanks for the answer. There are no better way to set name without setAttribute? This is very ugly since I'm using className and innerText directly. (I didnt downvote you) – Davelon Sahz Oct 31 '22 at 22:00
  • 1
    @DavelonSahz Nope, this is the only way (there are other ways but they're longer and pointless) that you should use. See [this question](https://stackoverflow.com/questions/8426461/javascript-setattribute-v-s-element-attribute-value-to-set-name-attribut) for why. – kelsny Oct 31 '22 at 22:02