function add() {
  var e_type = document.createElement("p");

  var p_type = document.getElementById("self");

  var text = document.createTextNode("I am a slow walker, but I never walk back.");

  e_type.appendChild(text);

  p_type.appendChild(e_type);

  var pattribute = document.createAttribute("id");

  pattribute.value = "test";

  element.setAttributeNode(pattribute);
}

#test {
  color: blue;
  font-style: bold;
}

<div id="self">

  <p>Hello, Thought of the Day</p>

</div>

<button onclick="add()">Click me</button>





:-添加的元素文本颜色不会因使用createAttribute而改变,而是
   其余的标签正在使用其ID(测试)更改其颜色。

最佳答案

element.setAttributeNode(pattribute);


是错的

如果您想为新p设置样式

e_type.setAttributeNode(pattribute);


如果您需要同时设置它们的样式

p_type.setAttributeNode(pattribute);

07-23 03:37