JavaScript Adding an ID attribute to another created Element
Asked Answered
I

3

87

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:

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:

  <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>
Involution answered 28/10, 2013 at 0:53 Comment(0)
G
175

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

myPara.setAttribute("id", "id_you_like");
Garrot answered 28/10, 2013 at 1:8 Comment(2)
This replaces the existing id if there is one. How do you append an id to an existing idSummersault
@PA-GW You can't. An HTML element can only have one id, since it's used to uniquely identify the element.Electronic
P
73

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

myPara.id = ID;
Parallelize answered 12/2, 2015 at 7:43 Comment(0)
O
4

You can use dot notation.

myPara.id = 'anyNameYouLike'; 
Omniscience answered 12/5, 2021 at 17:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.