简体   繁体   English

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

[英]JavaScript Adding an ID attribute to another created Element

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.代码创建了一个元素“p”,然后我将它附加到 HTML 中的“div”。 I would like that "p" I just created have an unique identifier (ID) and set the name of the ID.我希望我刚刚创建的“p”有一个唯一标识符 (ID) 并设置 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.所以稍后当用户想要删除最后一个创建的元素时,它将能够获取 ID 以便它可以 removeChild。 Here is the code:这是代码:

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>

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

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

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

myPara.id = ID;

您可以使用点表示法。

myPara.id = 'anyNameYouLike'; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM