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 by this.

Let's create an example object

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

We have a simple object, inside of which there are data such as name (first name), last_name (surname) and website (website). The data can be absolutely anything, but for the purposes of this record, it will be just that.

Adding a new element

obj.country = "en"; // 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"

Everything is clear in the code above, but just to be clear: you can add new values ​​to an object in the object syntax using "." and a 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 within 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 new object"; obj.other_obj.second = "second";

We have created two new values ​​first and second inside other_obj .

Removing an element

delete obj.name; // returns true

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

obj = (); // Make 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?

Straight 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 everything 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 after the reference Node Node , a new Node is added
  • If after that the reference Node 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 sibling after
  • First item
Sibling after
  • First item
  • Third item

The insertBefore() method is used like parentNode.insertBefore() . So to emulate this and make the 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 extending DOM 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 yours.

Allows 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 inlining 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 this question already has too many answers, but none of them met my exact requirements.

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

Because a null referenceNode requires you to insertBefore the parent, we need to know the parent - insertBefore is a parentNode method, so it has access to the parent's parentNode in this way; our function does not exist, so we need to pass 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.

Hello! Using JavaScript, you can not only find elements on the page (read 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 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 it.

Adding an element

Consider a small example:

Varel = document.createElement("div"); var elText = document.createTextNode("Hello World");

As you can see from the example, the elem variable will store a reference to the new div element. However, as you understand, creating elements is not enough, because 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 given 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

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

But it is not necessary to have an additional text node to create text inside an element, for this there is a textContent property that allows you to directly assign text to an element.

Var el = document.createElement("h3"); el.textContent = "Hello I'm 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 top of the div's collection of child nodes:

VarartDiv = document.querySelector("div.article"); // create element var el = document. createElement("h2"); // create text for it var eltxt = document. createTextNode("Hello World"); // add text to the element as a child el.appendChild(eltxt); // get the first element to be added before var firstEl = artDiv.firstChild.nextSibling; // add an element to the div 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 actually 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. For this, a separate cloneNode() method is used.

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

The cloneNode() method must be passed as a parameter boolean: if you pass true, then the element will be copied along with all child nodes; if you pass false, then it will be copied without child nodes. AT this example we copy the element along with its content and add it to the end of the web page.

Removing an element

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

VarartDiv = document.querySelector("div.article"); // find the node to be removed - the first paragraph var removNode = document.querySelectorAll("div.article p"); // remove 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.

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

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

RESULTS.

The following methods are used to create an element:

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

document.createTextNode(text)- creates a text node

Methods for Inserting and Removing Nodes

  • parent.appendChild(el)- adds 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 the element, if the parameter bool=true then the element is copied with all child elements, and if false then without child elements

Tasks

Function to insert elements

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