[ITEM 5] QUESTION: How to create and add an element?
Creating and adding new elements to the document is one of the most common tasks when developing web applications using JavaScript. This process consists of two main stages: direct creation of the node in the browser's memory and its subsequent integration into the existing DOM tree. To create a new node, the document.createElement method is used, which accepts a string with the tag name, for example, document.createElement('div'). Once the element is created, you can assign classes, attributes, and text content to it, after which it must be inserted into the page.
To add the created element, there are several methods depending on where exactly it needs to be placed. The classic and most versatile method is parent.appendChild(el), which adds the node to the very end of the specified parent's child list. If you need to place an element before a specific existing child element, the parent.insertBefore(el, ref) method is used, where the first argument is the new element, and the second is the reference element before which the insertion will occur.
The modern JavaScript standard offers more flexible and convenient methods for working with nodes. The el.append() and prepend() methods allow adding elements inside the parent element at the very end or at the very beginning, respectively. In addition, append and prepend accept not only nodes but also plain text strings, and allow adding multiple elements in a single call.
For even more precise positioning, the insertAdjacentHTML and insertAdjacentElement methods are used. They allow inserting markup or elements relative to the chosen element at four points: before the element itself, immediately after its opening tag, before the closing tag, or after the element itself. The correct choice of method depends on your application architecture and performance requirements.