Last Updated on 2022-04-28 by Clay
Recently, I got a need for create a new element in web page dynamically. In fact, I need to add some checkbox items via Javascript.
To solve this problem, I tried to use appendChild()
function in Javascript to create the child object at the specific element, and it works.
The following is my code and explanation, take the checkbox as example.
Sample Code
We well know, the checkbox element in HTML combines checkbox and label; checkbox used for user to check, the label just used to display the text.
So we can create a div block which has a specific id, and we can use id to get the element, then use appendChild()
to add some new elements.
(I CANNOT PASTE MY HTML CODE! SO I TAKE A SCREENSHOT...)
Output:
References
- https://stackoverflow.com/questions/11017509/add-onclick-event-to-document-createelementth
- https://www.w3schools.com/jsref/met_node_appendchild.asp
- https://stackoverflow.com/questions/6142806/how-to-use-the-addchild-method-of-javascript-to-add-a-node-to-my-div