Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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> 
like image 572
king_sw4 Avatar asked Oct 28 '13 00:10

king_sw4


People also ask

How do you append a ID to an element?

Use setAttribute() Function to Add id to an Element in JavaScript. For pre-existing and new HTML elements, setAttribute() function and . id property is used.

Can I use ID for multiple elements?

The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.

Can I get multiple elements by ID JavaScript?

Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements.


Video Answer


1 Answers

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

myPara.setAttribute("id", "id_you_like"); 
like image 198
Johann Echavarria Avatar answered Sep 21 '22 06:09

Johann Echavarria