JavaScript - working with DOM elements. Creating an element. JavaScript - DOM: adding and removing nodes Inserting an element into the dom javascript

💖 Do you like it? Share the link with your friends

If you need to create an HTML element and you don't know how to implement it, then you've come to the right place. This article will not only look at an example of creating an element, but also write a universal function with which you can create a new element, add various attributes to it, and fill it with text.

But first, let's start with something simple. In creating a new element, we will use the methods of the DOM object, namely:

* document.createElement(param) - this method is used directly to create an element. As a parameter, it takes the name of the element being created. Returns a link to the created element.

document.createElement('div'); // will create a div element.

* document.appendChild(param) – this method is used to add an element to the HTML code. Takes a link to the created element as a parameter;

var parent = document.getElementsByTagName("BODY"); //get a link to the body element

var elem = document.createElement(‘div’);// will create a div element

parent.appendChild(elem); // adds an element, where parent is the link where our element will be added, in this case it is the body body;

* document.createTextNode() - the method is used to place text inside an element.

An example of creating an element.

function createElem() (

Var newP = document.createElement("p");

NewP.className = "elemClass";

NewP.id = "myPId";

NewP.style.width = "100px";

NewP.style.height = "300px";

NewP.style.background = "#c5c5c5";

NewP.style.color = "#000";

Var text = "text to insert";

Var textNode = document.createTextNode(text);

NewP.appendChild(textNode);

Parent.appendChild(newP);

In the createElem function, the parent variable is a reference to the element (body) in which the new element will be placed. Then a new element P is created, the attributes id, class, style are added to it, and the values ​​of these attributes are set. Then a text node is created and added to our new element. After all this, the element itself is added to the body body. To make a large number of new elements you will have to work hard, because... you may need to place them in different places on the web page, e.g. attach to different elements.

An example of creating an element using a universal function.

This function will help you create a new element, add various attributes to it, attach a text node to it, place it before or after the specified element, or replace the element with a newly created element. Only the name argument is required.

function createElement(name, attrs, style, text, past_id, position, changed) (

Var parent = document.getElementsByTagName("BODY");

Var e = document.createElement(name);

If (attrs) (

For (key in attrs) (

If (key == "class") (

E.className = attrs;

) else if (key == "id") (

E.id = attrs;

) else (

E.setAttribute(key, attrs);

If (style) (

For (key in style) (

E.style = style;

If (text) (

E.appendChild(document.createTextNode(text));

Parent.appendChild(e);

If(past_id)(

Var old_elem = document.getElementById(past_id);

If(position=="before")(

Parent.insertBefore(e,old_elem)

)else if(position=="after")(

InsertAfter(parent,e,old_elem);

If(changed!="" && changed==true)(

Parent.removeChild(old_elem);

Options:

Name – element name;

Attrs – attributes of the created element;

Style – styles of the created element;

Text – inserted text;

Past_id – id of the element next to which our element will be located;

Position - can take two values ​​before, after;

Changed – a flag that takes two values: true or false. If this parameter is set to true, the old element will be replaced with a new one;

As an example, let's create a DIV element with attributes, and replace the old element with the newly created one.

createElement("div",

("class": "myDivCSSClass", "id": "myDivId","align":"center"),

("width": "200px", "height": "250px", "background": "#3B9D00", "color": "#fff"),

"here is my text",

"test",

"before"

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 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 object for example 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.

Deleting an element delete obj.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.



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 general 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

Please note that the DOM extension may be wrong decision 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.

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 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 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, delete everything child nodes for an element with 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.


  • tell friends