HTML DOM

JS DOM Elements

Manipulating DOM Elements

JavaScript DOM elements are created and modified with createElement.

Introduction to DOM Elements

The Document Object Model (DOM) represents the structure of a document as a tree of objects. Each element in an HTML document is represented by a DOM element, which can be manipulated using JavaScript. This allows developers to dynamically change the content and structure of web pages.

Creating a DOM Element with createElement

The createElement method is used to create a new HTML element. This element can then be customized and added to the DOM. The syntax for createElement is straightforward:

Here, tagName is the type of element you want to create, such as 'div', 'span', or 'p'.

Adding Attributes and Content

Once an element is created, you can set its attributes and content. Use the setAttribute method to add attributes, and the textContent or innerHTML properties to add content:

Appending Elements to the DOM

After creating and customizing an element, you need to add it to the DOM. This is done using the appendChild method, which attaches the new element as a child of a specified parent element:

Practical Example: Creating a List

Let's create a practical example to demonstrate how to use createElement to build a dynamic list:

This code creates an unordered list with three items: Apple, Banana, and Cherry. The list is then appended to the document body, making it visible on the web page.

Conclusion

Using the createElement method in JavaScript allows you to dynamically create and modify HTML elements within the DOM. This capability is essential for developing interactive web applications. In the next post, we'll explore how to manipulate the HTML content of DOM elements.

Previous
DOM Methods