Html JavaScript 将 ID 属性添加到另一个创建的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19625646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:48:10  来源:igfitidea点击:

JavaScript Adding an ID attribute to another created Element

javascripthtmlfunctiondomsetattribute

提问by king_sw4

I have some code here that will do the following. The code creates an element "p" then I append it to a "div" in the HTML. I would like that "p" I just created have an unique identifier (ID) and set the name of the ID. So later on when the user wants to delete the last created element it will be able to get the ID so it can removeChild. Here is the code:

我在这里有一些代码可以执行以下操作。代码创建了一个元素“p”,然后我将它附加到 HTML 中的“div”。我希望我刚刚创建的“p”有一个唯一标识符 (ID) 并设置 ID 的名称。所以稍后当用户想要删除最后一个创建的元素时,它将能够获取 ID 以便它可以 removeChild。这是代码:

JavaScript:

JavaScript:

  var $ = function (id)
  {
      return document.getElementById(id);
  }

  function ShowResponse ()
  {
  var myResponse = $("myresponse").value;

  var myPara = document.createElement("p");
  var myDiv = $("mydiv");
  myDiv.appendChild(myPara);

  var myID = document.createElement("id");
  myID.setAttribute("value", ID)

  var myText = document.createTextNode(myResponse);
  myPara.appendChild(myText);
  }

  function RemoveResponse ()
  {

  }

  window.onload = function ()
  {
      $("showresponse").onclick = ShowResponse;
      $("removeresponse").onclick = RemoveResponse;
  }

HTML:

HTML:

  <body>
  <div id="mydiv">
  <h1>Practice</h1>

  <p>Hi There</p>
  <p>How are you?</p>

  <p>
<input type="text" id="myresponse">
<br><input type="button" id="showresponse" value="Show Response">
<input type="button" id="removeresponse" value="Remove Response">
  </p>

  <hr>
 </div>

 </body>

回答by Johann Echavarria

Since id is an attribute don't create an id element, just do this:

由于 id 是一个属性,因此不要创建 id 元素,只需执行以下操作:

myPara.setAttribute("id", "id_you_like");

回答by Ja?ck

You set an element's id by setting its corresponding property:

您可以通过设置元素的相应属性来设置元素的 id:

myPara.id = ID;