Js dynamic creation of elements. JavaScript: How to add a new element to an object? Example: show message

In this post I want to tell you how to add or remove an element from an object in JavaScript. It's very simple, but many beginners, like me before, often get confused about it.

Let's create an example object

var obj = ( name: "alex", last_name: "petrov", website: "site", );

We have a simple object that contains data such as name, last_name and website. The data can be absolutely anything, but for the purposes of this post it will be exactly that.

Adding a new element

obj.country = "ru"; // will add new key"country" into an object with the value "ru" obj["city"] = "Moscow"; // will also add a new key, only "city" with the value "Moscow"

The code above is clear, but just to clarify: you can add new values ​​to an object in object syntax using "." and the key or the usual array format. If you declare it as an array, then obj is still an object, since you previously designated it that way thanks to () .

Create an object inside an object

obj.other_obj = (); // create a new value other_obj in obj and make it an object

Now let's add some data there:

Obj.other_obj.first = "first key of the new object"; obj.other_obj.second = "second";

We created two new values, first and second, inside other_obj.

Removing an element

deleteobj.name; // returns: true

You can use delete , which can remove elements from objects. You can't delete the entire object this way, but if you need to, you can do this:

Obj = (); // Makes the object empty again

That's all, if you still have any questions about objects in JavaScript, write a comment below, I will try to help you.

This is the fourth part of posts devoted to native equivalents of jQuery methods. You may want to read this before continuing.

In this article we will look at ways to create, insert, move and delete elements. And although jQuery already contains a large number of useful methods, you will be surprised to know that all this can be easily done using native methods.

Manipulations with HTML code of elements

jQuery
// get var html = $(elem).html(); // set $(elem).html("
New html
");
Native JS
// get var html = elem.innerHTML; // set elem.innerHTML = "
New html
";

Element text manipulation

jQuery
// get var text = $(elem).text(); // set $(elem).text("New text");
Native JS
// get var text = elem.textContent; // set elem.textContent = "New text";

Creating an element

jQuery
$("
");
Native JS
document.createElement("div");

Adds content to the end of elements

jQuery
$(parentNode).append(newNode);
Native JS
parentNode.appendChild(newNode);

Adds content to the beginning of elements

jQuery
$(referenceNode).prepend(newNode);
Native JS
referenceNode.insertBefore(newNode, referenceNode.firstElementChild); // or referenceNode.insertAdjacentElement("afterbegin", newNode); // FF 48.0+, IE8+

Insert directly before an Element

jQuery
$(referenceNode).before(newNode);
Native JS
referenceNode.parentNode.insertBefore(newNode, referenceNode); // or referenceNode.insertAdjacentElement("beforebegin", newNode); // FF 48.0+, IE8+

Insert directly after an Element

jQuery
$(referenceNode).after(newNode);
Native JS
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextElementChild); // or referenceNode.insertAdjacentElement("afterend", newNode); // FF 48.0+, IE8+

Note: 'beforebegin' and 'afterend' will only work if the referenceNode is in the DOM tree and has a parent element.

Look at the following:

ReferenceNode.insertAdjacentElement(position, node);

The insertAdjacentElement method takes two parameters:

  • position - position relative to referenceNode, must be one of the following:
    • 'beforebegin' - Before the element itself.
    • ‘afterbegin’ — Inside the element, before the first child.
    • 'beforeend' - Inside the element, after the last child.
    • ‘afterend’ - After the element itself.
  • node — node to insert
Text Content

Some Text
Some Text
var elem1 = document.getElementById("elem1"); var elem2 = document.getElementById("elem2"); elem1.insertAdjacentElement("beforeend", elem2); // result
Some Text
Some Text

The insertAdjacentElement method is cleaner and more intuitive than the insertBefore method, but the latter is better supported in older browsers.

Adding elements multiple times

It is also worth noting that adding an element to a node that is located in the DOM tree will lead to redrawing. This is not very good because the browser must recalculate the size and position of the new element, which will also lead to changes to the element's descendants, ancestors, and elements that appear after it in the DOM. If you are adding a lot of elements to the DOM, this may take some time.

To avoid this, you can add it with DocumentFragment. A document fragment is a document object that exists only in memory, so adding to it will not cause any reflow.

Let's say we need to add 100 li elements to a ul element that is present in the DOM tree:

// Get the element that will contain our items var ul = document.querySelector("ul"); // make 100 list elements for (var i = 1; i< 100; i++) { var li = document.createElement("li"); // append the new list element to the ul element ul.appendChild(li); }

In the above example, the li elements are added directly to the ul element, which is located in the DOM tree, hence will result in a redraw on each iteration - that's 100 changes!

Let's find a better way.

// Get the element that will contain our items var ul = document.querySelector("ul"); // create a document fragment to append the list elements to var docFrag = document.createDocumentFragment(); // make 100 list elements for (var i = 1; i< 100; i++) { var li = document.createElement("li"); // append the new list element to the fragment docFrag.appendChild(li); } // append the fragment to the ul element ul.appendChild(docFrag);

In the same example, the li elements are added to the document fragment in memory, so that the reflow will trigger when the fragment is added to the ul element. This method will reduce the number of redraws from 100 to 1.

Removing an element

jQuery
$(referenceNode).remove();
Native JS
referenceNode.parentNode.removeChild(referenceNode); // or referenceNode.remove(); // FF 23.0+, 23.0+, Edge (No IE support)

In this lesson we will learn how to create element nodes (createElement) and text nodes (createTextNode). We will also consider methods designed for adding nodes to the tree (appendChild, insertBefore) and for removing nodes from the tree (removeChild).

Adding Nodes to a Tree

Adding a new node to a tree is usually carried out in 2 stages:

  1. Create the required node using one of the following methods:
  • createElement() - creates an element (node) with specified name(tag). The createElement(element) method has one required parameter (element) - this is a string containing the name of the element (tag) to be created. You must specify the name of the element (tag) in the parameter in capital letters. As a result this method returns the element that was created.
  • createTextNode() - creates a text node with the specified text. The createTextNode(text) method has one required parameter (text) - this is a string containing the text of the text node. As a result, this method returns the text node that was created.
  • Specify the location in the tree where the node should be inserted. To do this, you must use one of the following methods:
    • appendChild() - adds a node as the last child of the element on which this method is called. The appendChild(node) method has one required parameter: the node you want to add. As a result, this method returns the added node.
    • insertBefore() - inserts a node as a child node of the element on which this method is called. The insertBefore(newNode,existingNode) method has two parameters: newNode (required) is the node you want to add, existingNode (optional) is the child node of the element before which you want to insert the node. If the second parameter (existingNode) is not specified, then this method will insert it at the end, i.e. as the last child node of the element for which this method is called. The insertBefore() method returns the inserted node as its result.

    For example:

    • Computer
    • Laptop
    • Tablet

    Let's consider a more complex example in which we add to the tree an LI node containing a text node with the text "Smartphone" at the end of the ul list.

    To do this you need to do the following:

    1. Create an element (node) LI.
    2. Create a text node containing the text "Smartphone".
    3. Add the created text node as the last child node of the newly created LI element
    4. Add the newly created LI node as the last child node of the ul element
    //create an element (node) li var elementLI = document.createElement("li"); //create a text node containing the text "Smartphone" var textSmart= document.createTextNode("Smartphone"); //append the created text node as the last child element to the newly created LI element elementLI.appendChild(textSmart); //get the element to which the created li node will be added as a child var elementUL = document.getElementById("list"); //add the created li element as the last child element to the UL with id="list" elementUL.appendChild(elementLI);

    AppendChild() and insertBefore() methods when working with existing nodes

    Working with existing nodes using the appendChild() and insertBefore() methods is also carried out in 2 stages:

    1. Get an existing node in the tree.
    2. Specify the location where the node should be inserted using the appendChild() or insertBefore() method. This will remove the node from its previous location.

    For example, add an existing li element containing the text “Tablet” to the beginning of the list (this will remove it from the previous place):

    //get the UL element containing the list by its id var elementUL = document.getElementById("list"); //get the li element containing the text node "Tablet" var elementLI = elementUL.childNodes; //add an element to the beginning of the list //in this case it will be removed from its original location elementUL.insertBefore(elementLI,elementUL.firstChild);

    Exercise

    • There are two lists in the document. You need to move elements from the second list to the first.
    • Create a list, a text field and 2 buttons. Write code in JavaScript that, depending on the button pressed, adds the text in the text field to the beginning or end of the list.

    Removing nodes

    Removing a node from a tree is carried out in 2 stages:

    1. Get (find) this node in the tree. This action is typically performed by one of the following methods: getElementById() , getElementsByClassName() , getElementsByTagName() , getElementsByName() , querySelector() , or querySelectorAll() .
    2. Call the removeChild() method on the parent node, which must be passed as a parameter the node that we want to remove from it.
      The removeChild() method returns the removed node as its value, or null if the node we wanted to remove did not exist.

    //find the node we want to delete var findElement = document.getElementById("notebook"); //call the removeChild method on the parent node //and pass it the found node as a parameter findElement.parentNode.removeChild(findElement);

    For example, remove the last child element of an element that has id="myID" :

    //get the element that has id="myID" var myID = document.getElementById("myID"); //get the last child node of the element myID var lastNode = myID.lastChild; //because we don't know if the last child node of the element is an element, //then we'll use while loop to find the last child element of an element myID //while the element has a node and its type is not 1 (i.e. it is not an element) do while(lastNode && lastNode.nodeType!=1) ( //go to the previous node lastNode = lastNode.previousSibling; ) //if we found an element at the node myID if (lastNode) ( //then it must be removed lastNode.parentNode.removeChild(lastNode); )

    For example, remove all child nodes of an element that has id="myQuestion" :

    //get the element from which we want to remove all its child nodes var elementQuestion = document.getElementById("myQuestion"); //while there is the first element while (elementQuestion.firstElement) ( //remove it elementQuestion.removeChild(element.firstChild); )

    Exercise

    1. Write a function that removes all text nodes from an element.
    2. There are 2 lists (), write a JavaScript code that removes all elements from list 1 and 2.