JS createElement: создание элементов на странице
JavaScript method `createElement()` is used to create a new HTML element dynamically. With this method, you can create an element with specified tag name and add it to the DOM (Document Object Model) tree as a child of the given parent node. This is a powerful method that improves the functionality and flexibility of your web pages, especially when used with other DOM manipulation methods.
Here is an example code snippet to create a new `div` element with a specified `id` and `class` attributes using `createElement()` method:
js
//Create a new div element
let newDiv = document.createElement("div");
//Set attributes for the new div element
newDiv.setAttribute("id", "test-div");
newDiv.setAttribute("class", "content");
//Add content to the new div element
let newContent = document.createTextNode("This is a new div element!");
newDiv.appendChild(newContent);
//Add the new div element to the DOM
let container = document.getElementById("parent-div");
container.appendChild(newDiv);
In this example, we have first created a new `div` element using the `createElement()` method. We have then added a unique `id` and `class` attributes to this element using the `setAttribute()` method. After that, we have added some content to the new div element using the `createTextNode()` method and appended it as a child to the new `div`. Finally, we have used the `appendChild()` method to add this new `div` element as a child to its parent element in the DOM.
The `createElement()` method is a versatile and powerful tool that can be used to create any type of HTML element dynamically. By combining this method with other DOM manipulation methods, you can create rich and dynamic web pages that are more interactive and user-friendly.