• JavaScript: How to add a new element to an object? JavaScript: creating DOM fragments Javascript adding an element

    Last update: 11/1/2015

    To create elements, the document object has the following methods:

      createElement(elementName) : Creates an html element whose tag is passed as a parameter. Returns the created element

      createTextNode(text) : Creates and returns a text node. The node text is passed as a parameter.

    var elem = document.createElement("div"); var elemText = document.createTextNode("Hello world");

    So the elem variable will store a reference to the div element. However, simply creating elements is not enough; they still need to be added to the web page.

    To add elements, we can use one of the Node object's methods:

      appendChild(newNode) : adds a new node newNode to the end of the collection of child nodes

      insertBefore(newNode, referenceNode) : adds a new node newNode before the referenceNode

    We use the appendChild method:

    Article title

    First paragraph

    Second paragraph

    var articleDiv = document.querySelector("div.article"); // create an element var elem = document.createElement("h2"); // create text for it var elemText = document.createTextNode("Hello world"); // add text to the element as a child elem.appendChild(elemText); // add an element to the div block articleDiv.appendChild(elem);

    First we create a regular h2 header element and a text node. Then we add a text node to the header element. Then we add the title to one of the elements of the web page:

    However, we don't have to create an additional text node to define text inside an element, since we can use the textContent property and assign text to it directly:

    Var elem = document.createElement("h2"); elem.textContent = "Hello world";

    In this case, the text node will be created implicitly when the text is set.

    Now let's look at how to add a similar element to the beginning of the collection of child nodes of a div block:

    Var articleDiv = document.querySelector("div.article"); // create an element var elem = document.createElement("h2"); // create text for it var elemText = document.createTextNode("Hello world"); // add text to the element as a child elem.appendChild(elemText); // get the first element that will be preceded by the addition var firstElem = articleDiv.firstChild.nextSibling; // add an element to the div block before the first node articleDiv.insertBefore(elem, firstElem);

    If we need to insert a new node at the second, third or any other place, then we need to find the node before which we need to insert using combinations of the firstChild/lastChild and nextSibling/previousSibling properties.

    Copying an element

    Sometimes elements are quite complex in composition, and it is much easier to copy them than to create content from them using separate calls. To copy existing nodes from a Node object, you can use the cloneNode() method:

    Var articleDiv = document.querySelector("div.article"); // clone the articleDiv element var newArticleDiv = articleDiv.cloneNode(true); // add to the end of the body element document.body.appendChild(newArticleDiv);

    The cloneNode() method is passed a Boolean value as a parameter: if true is passed, the element will be copied with all child nodes; if false is passed, then it is copied without child nodes. That is, in this case we copy the node with all its contents and then add it to the end of the body element.

    Removing an element

    To remove an element, call the removeChild() method of the Node object. This method removes one of the child nodes:

    Var articleDiv = document.querySelector("div.article"); // find the node that we will delete - the first paragraph var removableNode = document.querySelectorAll("div.article p"); // remove the node articleDiv.removeChild(removableNode);

    In this case, the first paragraph is removed from the div block

    Replacing an element

    To replace an element, use the replaceChild(newNode, oldNode) method of the Node object. This method takes a new element as the first parameter, which replaces the old element oldNode passed as the second parameter.

    Var articleDiv = document.querySelector("div.article"); // find the node that we will replace - the first paragraph var oldNode = document.querySelectorAll("div.article p"); // create an element var newNode = document.createElement("h2"); // create text for it var elemText = document.createTextNode("Hello world"); // add text to the element as a child element newNode.appendChild(elemText); // replace the old node with a new one articleDiv.replaceChild(newNode, oldNode);

    In this case, we replace the first paragraph with an h2 heading.

    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:

  • Create the required node using one of the following methods:
    • createElement() - creates an element (node) with the 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. The name of the element (tag) in the parameter must be 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:

  • Create an element (node) LI.
  • Create a text node containing the text "Smartphone".
  • Add the created text node as the last child node of the newly created LI element
  • 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:

  • Get an existing node in the tree.
  • 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:

  • 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() .
  • 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 a while loop to find the last child of the element myID //as long as the element has a node and its type is not 1 (i.e. it's not an element) execute while (lastNode && lastNode.nodeType!=1) ( //go to the previous node lastNode = lastNode.previousSibling; ) //if we found an element at the myID node 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
  • Write a function that removes all text nodes from an element.
  • There are 2 lists (), write a JavaScript code that removes all elements from list 1 and 2.
  • Hello! Using JavaScript, you can not only find elements on a page (read about how to do this) but also create elements dynamically and add them to the DOM. How to do this will be discussed in this lesson.

    In order to create a new element on a web page, the document object has the following methods:

    • createElement(elementName) : creates a new element, any HTML page tag must be passed as a parameter, returns an HTML element
    • createTextNode(text) : Creates a text node and returns the same.

    Adding an element

    Let's look at a small example:

    Var el = document.createElement("div"); var elText = document.createTextNode("Hello world");

    As you can see from the example, the elem variable will store a link to the new div element. However, as you understand, creating elements is not enough; they still need to be added to the web page. After all, when we create elements in this way, they seem to be in some kind of virtual space or in memory, but in order to display them on a web page, there are special methods.

    The following methods are used to add elements to a web page:

    • appendChild(newNode) : adds a new element to the end of the element on which this method was called
    • insertBefore(newNode, referenceNode) : adds a new node before the node specified as the second parameter.

    Let's look at an example of attaching an element to a web page using the appendChild method:

    Article title

    First paragraph

    Second paragraph

    var article = document.querySelector("div.article"); // create an element var el = document.createElement("h3"); // create text for it var elTxt = document.createTextNode("Hello world"); // add text to the element as a child element el.appendChild(elTxt); // add an element to the div block article.appendChild(el);

    The example created a normal h3 header element and a text node. The text node is then added to the title element. The title is then added to one of the web page elements so that it can be seen on the page.

    But it is not at all necessary to have an additional text node to create text inside an element; for this, there is the textContent property, which allows you to directly assign text to an element.

    Var el = document.createElement("h3"); el.textContent = "Hi I'm the title";

    In this case, the text will be created implicitly when setting the text directly.

    And let's also look at how to add this element to the beginning of a collection of child nodes of a div:

    Var artDiv = document.querySelector("div.article"); // create an element var el = document.createElement("h2"); // create text for it var eltxt = document.createTextNode("Hello world"); // add text to the element as a child element el.appendChild(eltxt); // get the first element that will be preceded by the addition var firstEl = artDiv.firstChild.nextSibling; // add an element to the div block before the first node artDiv.insertBefore(el, firstEl);

    If you suddenly need to add a new node to the second, third or any other place, then you need to find the node before which you need to insert it using the following properties firstChild/lastChild or nextSibling/previousSibling.

    Copying an element

    There are situations when the elements are quite complex in composition, and it is easier to copy them. A separate cloneNode() method is used for this.

    Var artDiv = document.querySelector("div.article"); // clone the articleDiv element var newArtDiv = artDiv.cloneNode(true); // add to the end of the body element document.body.appendChild(newArtDiv);

    You must pass a Boolean value as a parameter to the cloneNode() method: if you pass true, the element will be copied along with all child nodes; if you pass false, it will be copied without child nodes. In this example, we copy the element along with its contents and add it to the end of the web page.

    Removing an element

    In order to remove an element, you need to call the removeChild() method. This method will remove one of the child nodes:

    Var artDiv = document.querySelector("div.article"); // find the node that we will delete - the first paragraph var removNode = document.querySelectorAll("div.article p"); // remove the node artDiv.removeChild(removNode);

    This example will remove the first paragraph from the div block

    Replacing an element

    To replace one element with another, use the replaceChild(newNode, oldNode) method. This method takes a new element as the 1st parameter, which replaces the old element passed as the 2nd parameter.

    Var artDiv = document.querySelector("div.article"); // find the node that we will replace - the first paragraph var old = document.querySelectorAll("div.article p"); // create an element var new = document.createElement("h3"); // create text for it var elemtxt = document.createTextNode("Hello world"); // add text to the element as a child element new.appendChild(elemtxt); // replace the old node with a new one artDiv.replaceChild(new, old);

    In this example, we replace the first paragraph with the h2 heading we just created.

    RESULTS.

    To create an element, the following methods are used:

    document.createElement(tag) - creates a new element.

    document.createTextNode(text) - creates a text node

    Methods for inserting and removing nodes

    • parent.appendChild(el) - appends an element to the end of an existing element
    • parent.insertBefore(el, nextSibling) - inserts an element before an existing element
    • parent.removeChild(el) - removes an element
    • parent.replaceChild(newElem, el) - replaces one element with another
    • parent.cloneNode(bool) - copies an element, if the parameter bool=true then the element is copied with all child elements, and if false then without child elements
    Tasks Function of inserting elements

    Write a function insertAfter(newEl,oldEl) that inserts one element after another into the function itself, the elements themselves are passed as parameters.



    remove js element (12)

    Step 1. Prepare the elements:

    var element = document.getElementById("ElementToAppendAfter"); var newElement = document.createElement("div"); var elementParent = element.parentNode;

    Step 2. Add after:

    elementParent.insertBefore(newElement, element.nextSibling);

    JavaScript has insertBefore() but how can I insert an element after another element without using jQuery or another library?

    Straightforward JavaScript would be:

    Add:

    Element.parentNode.insertBefore(newElement, element);

    Add after:

    Element.parentNode.insertBefore(newElement, element.nextSibling);

    But, throw some prototypes in there for ease of use

    By creating the following prototypes, you will be able to call this function directly from the newly created elements.

      newElement.appendBefore(element);

      newElement.appendAfter(element);

    .appendBefore(element) Prototype

    Element.prototype.appendBefore = function (element) ( element.parentNode.insertBefore(this, element); ),false;

    .appendAfter(element)Prototype

    Element.prototype.appendAfter = function (element) ( element.parentNode.insertBefore(this, element.nextSibling); ),false;

    And to see it in action, run the following code snippet

    /* Adds Element BEFORE NeighborElement */ Element.prototype.appendBefore = function(element) ( element.parentNode.insertBefore(this, element); ), false; /* Adds Element AFTER NeighborElement */ Element.prototype.appendAfter = function(element) ( element.parentNode.insertBefore(this, element.nextSibling); ), false; /* Typical Creation and Setup A New Orphaned Element Object */ var NewElement = document.createElement("div"); NewElement.innerHTML = "New Element"; NewElement.id = "NewElement"; /* Add NewElement BEFORE -OR- AFTER Using the Aforementioned Prototypes */ NewElement.appendAfter(document.getElementById("Neighbor2")); div ( text-align: center; ) #Neighborhood ( color: brown; ) #NewElement ( color: green; ) Neighbor 1 Neighbor 2 Neighbor 3

    Ideally insertAfter should work similar to MDN. The code below will do the following:

    • If there are no children, a new Node is added
    • If there is no reference Node, a new Node is added
    • If there is a Node after the reference Node, a new Node is added
    • If the referenced Node then has children, then the new Node is inserted before that sibling
    • Returns a new Node

    Node extension

    Node.prototype.insertAfter = function(node, referenceNode) ( if (node) this.insertBefore(node, referenceNode && referenceNode.nextSibling); return node; );

    One common example

    Node.parentNode.insertAfter(newNode, node);

    See code running

    // First extend Node.prototype.insertAfter = function(node, referenceNode) ( if (node) this.insertBefore(node, referenceNode && referenceNode.nextSibling); return node; ); var referenceNode, newNode; newNode = document.createElement("li") newNode.innerText = "First new item"; newNode.style.color = "#FF0000"; document.getElementById("no-children").insertAfter(newNode); newNode = document.createElement("li"); newNode.innerText = "Second new item"; newNode.style.color = "#FF0000"; document.getElementById("no-reference-node").insertAfter(newNode); referenceNode = document.getElementById("no-sibling-after"); newNode = document.createElement("li"); newNode.innerText = "Third new item"; newNode.style.color = "#FF0000"; referenceNode.parentNode.insertAfter(newNode, referenceNode); referenceNode = document.getElementById("sibling-after"); newNode = document.createElement("li"); newNode.innerText = "Fourth new item"; newNode.style.color = "#FF0000"; referenceNode.parentNode.insertAfter(newNode, referenceNode); No children No reference node

    • First item
    No siblings after
    • First item
    Sibling after
    • First item
    • Third item

    The insertBefore() method is used like parentNode.insertBefore() . So to emulate this and make a parentNode.insertAfter() method we can write the following code.

    Node.prototype.insertAfter = function(newNode, referenceNode) ( return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); // based on karim79"s solution ); // getting required handles var refElem = document.getElementById(" pTwo"); var parent = refElem.parentNode; // creating

    paragraph three

    var txt = document.createTextNode("paragraph three"); var paragraph = document.createElement("p"); paragraph.appendChild(txt); // now we can call it the same way as insertBefore() parent.insertAfter(paragraph, refElem);

    paragraph one

    paragraph two

    Note that DOM expansion may not be the right solution for you, as stated in this article.

    Hovewer, this article was written in 2010 and things may be different now. So decide for yourself.

    Allows you to handle all scenarios

    Function insertAfter(newNode, referenceNode) ( if(referenceNode && referenceNode.nextSibling && referenceNode.nextSibling.nodeName == "#text") referenceNode = referenceNode.nextSibling; if(!referenceNode) document.body.appendChild(newNode); else if (!referenceNode.nextSibling) document.body.appendChild(newNode); else referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);

    This code works to insert a link element right after the last existing child inlining to inline a small css file

    Var raf, cb=function())( //create newnode var link=document.createElement("link"); link.rel="stylesheet";link.type="text/css";link.href="css/ style.css"; //insert after the lastnode var nodes=document.getElementsByTagName("link"); //existing nodes var lastnode=document.getElementsByTagName("link"); lastnode.parentNode.insertBefore(link, lastnode.nextSibling ); //check before insert try ( raf=requestAnimationFrame|| mozRequestAnimationFrame|| webkitRequestAnimationFrame|| msRequestAnimationFrame; ) catch(err)( raf=false; ) if (raf)raf(cb); else window.addEventListener("load",cb);

    I know there are already too many answers to this question, but none of them met my exact requirements.

    I need a function that has the exact opposite behavior of parentNode.insertBefore - that is, it should accept a null referenceNode (which is not accepted in response) and where insertBefore will insert into end insertBefore which he should insert into beginning, since otherwise there would be no way to paste to the original location with this function at all; for the same reason insertBefore inserts at the end.

    Since a null referenceNode requires you to insertBefore the parent, we need to know the parent - insertBefore is a method of parentNode , so it has access to the parent's parentNode that way; our function doesn't exist, so we need to pass the parent element as a parameter.

    The resulting function looks like this:

    Function insertAfter(parentNode, newNode, referenceNode) ( parentNode.insertBefore(newNode, referenceNode ? referenceNode.nextSibling: parentNode.firstChild); )

    If (! Node.prototype.insertAfter) ( Node.prototype.insertAfter = function(newNode, referenceNode) ( this.insertBefore(newNode, referenceNode ? referenceNode.nextSibling: this.firstChild); ); )

    node1.after(node2) creates ,

    where node1 and node2 are DOM nodes.

    If you've ever written JavaScript and had to write something like:
    var p = document.createElement("p");
    p.appendChild(document.createTextNode("Real fishfish."));
    var div = document.createElement("div");
    div.setAttribute("id", "new");
    div.appendChild(p);

    then this may be useful to you.

    Problem: When you create more than one element nested inside each other, the code becomes very complex.

    I offer a simple tool for solving the problem - the create() function (source code below). For example, let's create a paragraph of text:
    var el = create("p", ( ), "Farewell, Love!");

    Or a div with a paragraph and a link inside it:
    var div = create("div", ( id: "new", style: "background:#fff" ),
    create("p", ( align: "center" ),
    "intro: "
    create("a", ( href: "ua.fishki.net/picso/kotdavinchi.jpg" ),
    "picture"),
    ": end")
    );

    Or here we make a table:
    var holder = document.getElementById("holder2");
    var table;
    var td;
    holder.appendChild(
    table =
    create("table", (id: "ugly", cols:3),
    create("tbody", (),
    create("tr", (),
    create("td", ( width: "10%" ),
    "hello")
    td =
    create("td", ( style: "background: #fcc" ),
    "there")
    create("td", ( Class: "special2"), "everywhere")
    )
    );

    Please note: 1. IE requires a tbody element, otherwise it refuses to show the table.
    2. The class attribute conflicts with something, so you have to write it as Class. This does not seem to have any effect on the result.
    3. table = and tr = in the example allow you to save the created nested objects for further work with them.
    4. This code works in IE, Mozilla, and Opera. The function itself function create(name, attributes) (
    var el = document.createElement(name);
    if (typeof attributes == "object") (
    for (var i in attributes) (
    el.setAttribute(i, attributes[i]);

    If (i.toLowerCase() == "class") (
    el.className = attributes[i]; // for IE compatibility

    ) else if (i.toLowerCase() == "style") (
    el.style.cssText = attributes[i]; // for IE compatibility
    }
    }
    }
    for (var i = 2;i< arguments.length; i++) {
    var val = arguments[i];
    if (typeof val == "string") ( val = document.createTextNode(val) );
    el.appendChild(val);
    }
    return el;
    }


    We should thank Ivan Kurmanov for the idea,
    Original article with working examples: