23.07.2020

Remove - How to insert an element after another element in JavaScript without using a library? JavaScript - working with DOM elements. Creating an element Methods for adding elements to a page using js


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

then it may be useful to you.

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

I offer a simple tool for solving the problem - the create () function (source 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"),
"introduction: ",
create ("a", (href: "ua.fishki.net/picso/kotdavinchi.jpg"),
"picture"),
": the 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")
)
);

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. It seems that this has no 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;
}


Thanks to Ivan Kurmanov for the idea,
Original article with working examples:

In this lesson, we will learn how to create element nodes (createElement) and text nodes (createTextNode). We will also consider methods 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 done in 2 stages:

  1. Create the required node using one of the following methods:
  • createElement () - creates an element (node) with specified name(by tag). The createElement (element) method has one required parameter (element), which is a string containing the name of the element (tag) to create. The name of the element (tag) in the parameter must be specified 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), which is a string containing the text of the text node. As a result, this method returns the text node that was created.
  • Specify the place in the tree where you want to insert the node. To do this, you must use one of the following methods:
    • appendChild () - adds a node as the last child node of the element on which this method is called. The appendChild (node) method has one required parameter, which is the node you want to add. This method returns the added node as a result.
    • insertBefore () - inserts a node as a child node of the element for which this method is called. The insertBefore (newNode, existingNode) method has two parameters: newNode (required) - 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 of the element for which this method is called. The insertBefore () method returns the inserted node as a result.

    For example:

    • A computer
    • Notebook
    • Tablet

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

    To do this, you need to do the following:

    1. Create element (node) LI.
    2. Create a text node containing the text "Smartphone".
    3. Add the created text node as the last child to the newly created LI element
    4. Add newly created LI node as the last child 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"); // add the created text node as the last child 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 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. Indicate where you want to insert the node using the appendChild () or insertBefore () method. This will remove the node from the 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 Tablet text node var elementLI = elementUL.childNodes; // add an element to the beginning of the list // this will remove it from its original location elementUL.insertBefore (elementLI, elementUL.firstChild);

    Exercise

    • There are two lists in the document. You need to move items from the second list to the first.
    • Create list, text box and 2 buttons. Write code on JavaScript, which, depending on the button pressed, adds the text in the text box 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 usually performed by one of the following methods: getElementById (), getElementsByClassName (), getElementsByTagName (), getElementsByName (), querySelector (), or querySelectorAll ().
    2. Call the removeChild () method on the parent node, to which the node that we want to remove from it must be passed as a parameter.
      The removeChild () method returns the removed node 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 the found node as a parameter findElement.parentNode.removeChild (findElement);

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

    // get the element with id = "myID" var myID = document.getElementById ("myID"); // get the last child node of the element myID var lastNode = myID.lastChild; //t.k. we don't know if the last child of an element is an element, // then we use a while loop to find the last child element the element myID // while the element has a node and its type is not equal to 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 myID node if (lastNode) (// then it must be removed lastNode.parentNode.removeChild (lastNode);)

    For example, remove all child nodes from an element with id = "myQuestion":

    // get the element from which we want to remove all of 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 to remove all text nodes from an element.
    2. There are 2 lists (), write JavaScript to remove all items from list 1 and 2.
  • Last updated: 1.11.2015

    The document object has the following methods to create elements:

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

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

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

    Thus, the variable elem will hold the reference to the div element. However, just creating the elements is not enough, they still need to be added to the web page.

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

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

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

    Let's use the appendChild method:

    Article title

    First paragraph

    Second paragraph

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

    However, we do not need to create an additional text node to define the text inside the element, since we can use the textContent property and directly assign the text to it:

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

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

    Now let's see 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, preceded by the addition var firstElem = articleDiv.firstChild.nextSibling; // add an element to the div 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 a combination of the properties firstChild / lastChild and nextSibling / previousSibling.

    Copying an item

    Sometimes elements are quite complex in composition, and it is much easier to copy them than using separate calls to create from content. 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 as a parameter boolean: if true is passed, then the element will be copied with all child nodes; if false is passed, 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 item

    The removeChild () method of the Node object is called to remove an element. This method removes one of the child nodes:

    Var articleDiv = document.querySelector ("div.article"); // find the node to be removed - first paragraph var removableNode = document.querySelectorAll ("div.article p"); // remove the node articleDiv.removeChild (removableNode);

    This removes the first paragraph from the div.

    Element replacement

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

    Var articleDiv = document.querySelector ("div.article"); // find the node to 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 newNode.appendChild (elemText); // replace old knot new articleDiv.replaceChild (newNode, oldNode);

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

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

    Let's create an example object

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

    We have a simple object, inside which we have data such as name (first name), last_name (last name) and website (website). The data can be absolutely anything, but for the purposes of this recording, it will be that way.

    Adding a new item

    obj.country = "ru"; // add a new key "country" to the 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's syntax using "." and a key or regular array format. If you declare as an array, then obj is still an object, as 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 have created two new values, first and second, inside other_obj.

    Removing an item

    delete obj.name; // returns: true

    You can use delete, which can remove elements from objects. The entire object cannot be deleted in this way, but if you need it, then 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.

    This is the fourth part of a blog post covering the native jQuery method equivalents. You can read it before continuing.

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

    Manipulation 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
    ";

    Manipulating text of elements

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

    Element creation

    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 when the referenceNode is in the DOM tree and has a parent.

    Take a 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 - the 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 in the DOM tree will lead to redrawing. This is not very good, because the browser has to recalculate the size and position of the new element, which will also change 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, it may take a while.

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

    Let's say we need to add 100 li elements to the 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, li elements are added directly to the ul element, which is in the DOM tree, therefore, will lead to redrawing 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, li elements are added to the chunk of the document in memory, so the reflow will work when the chunk is added to the ul element. This method will reduce the number of redraws from 100 to 1.

    Removing an item

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

    2021
    maccase.ru - Android. Brands. Iron. news