The Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.
Creating DOM elements using js, adding text to the new element and appending the child to the Html body is not a hard task, it can be done in just a couple of lines of code. Let's see in the next example:
var div = document.createElement('div'); //creating element div.textContent = "Hello, World"; //adding text on the element document.body.appendChild(div); //appending the element
In the example above, on the first line, we are creating new div with the method
createElement() which has been called on the document object. In the method, we are passing an argument telling which element we want to be created. On the second line, we are using the
textContent property to add text to our newly created element. Lastly, on the third line, we are using the document, body property to call the
appendChild() method and pass our element we want to append to the body, in our case the newly created div element.
So as we can see, the code above is equivalent to:
<body> <div>Hello, World</div> </body>
Removing DOM elements is also simple and easy as creating DOM elements. Each DOM element has a property that’s the DOM element’s parent. To remove an element, we just need to call the
removeChild() method, and pass the child element we want to remove as an argument to the same method:
As you can see it is even simpler than creating elements!.
Create Element with jQuery
var div = $('<div/>').text("Hello, World").appendTo(document.body);