- innerHTML way: Directly assign HTML code to innerHTML property of parent element.
- appendChild way: Create DOM elements by document.createElement method, and append them to parent element by appendChild method.
As previous post, a example will be given here. We will create a div element, and append an anchor element to the div element, then append the div element to the end of body element.
1. innerHTML way:
Please see the following code snippet. It's very easy and intuitive. We directly assign the HTML code to innerHTML property of body element.
2. appendChild way:
Please see the following code snippet. The div and anchor elements are created by document.createElement method, and then appended to parent elements by appendChild method. The result of the following code snippet is the same as that of the above code snippet. At least there are no problems for me so far.
Personally I sometimes choose one way to create elements, sometimes the other way. My criteria for choosing is based on code readability. If one way can make the code more readable and understandable than the other, I will choose it. Hope this post would be helpful for those who need.