Following syntax will explain you how to use the id property to change, get and add a new id to the HTML element −
Selected_element.id = newID;
In above syntax, first we will select the HTML element whose ID we want to change using the HTML DOM, the use the id property with dot operator to assign a new id on right hand side of assignment operator.
Let us understand the practical implementation of the id property to change ID of an element in HTML document with code examples.
Step 1 − In the first step, we will add a input element to get the new ID as a input from the user and later we will change the ID of the same input element using the id property.
Step 3 − In the next step, we will grab the input element and display the initial id of the element to the users, so that they can easily see the change in the ID of element.
Step 5 − In the last step, we will display the new ID assigned to the element using the id property and assign the function as a value to the onclick event so that it can call it later when user clicks the button.
Below example will illustrate the use of the id property to change the id of the element in HTML document −
Let us see one more code example, where we will directly change the ID of the element inside the onclick event instead of passing function to it.
The algorithm of the above example and this example is almost similar. You just need to change the value passed inside the onclick event of the button element as shown in the below example.
The example below will explain you the changes you have to make in the previous algorithm to make it change the id of the input element as the previous example does −
In the above example, we can change the ID of the input element, but in this case, we cannot replace the previous id with an id of our choice as we are statically assigning the new ID value to the element.
In this article, we have learned about the method of changing the id of the element present in the HTML document with an id of your choice as well as a static id we want to give to the element that has to be unique and only the single element in the document which can contain that id.
- Related Articles
- How to change the element id using jQuery?
- How to test the id of an element using Protractor?
- How to find an element using the attribute “id” in Selenium?
- How can I get the ID of an DOM element using jQuery?
- How to remove all the elements from DOM using element ID in jQuery?
- How to select a single element which matches the given ID using jQuery?
- Change the width of element using CSS
- Change the height of element using CSS