the Internet Windows Android

JavaScript - DOM: Add and delete knots. JavaScript - Working with DOM elements

In this lesson, we will learn how to create nodes-elements (CreateElement) and text nodes (CreateTextNode). As well as consider methods intended to add nodes to the tree (AppendChild, InsertBefore) and to remove knots from the tree (Removechild).

Adding nodes to the tree

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

  1. Create a necessary node using one of the following methods:
  • createEelement () - Creates an element (node) with the specified name (tag). The CreateEelement (Element) method has one mandatory parameter (Element) is a string containing the name of the generated element (tag). Specify the name of the element (tag) in the parameter is necessary in capital letters. As a result, this method returns an element that was created.
  • createTextNode () - creates a text node with the specified text. The CreateTextNode (Text) method has one required parameter (text) is a string containing text node text. As a result, this method returns a text node that was created.
  • Specify the place in the tree where you want to insert a node. To do this, use one of the following methods:
    • appendChild () - adds a node as the last child element node for which this method is called. The AppendChild (Node) method has one required parameter. This node (Node) you want to add. As a result, this method returns the added node.
    • insertBefore () - inserts a node as a child node of an item for which this method is called. The insertBefore method (NewNode, ExistingNode) method has two parameters: newnode - the node you want to add, existingnode (optional) is a child element node in front of which, you need to insert a node. If the second parameter (existingnode) does not specify, then this method will insert it into the end, i.e. As the last subsidiary of the element for which this method is called. As a result, the INSERTBEFORE () method returns the inserted node.

    For example:

    • A computer
    • Notebook
    • The tablet

    Consider a more complex example in which I will add a 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 an element (node) Li.
    2. Create a text node containing the text "Smartphone".
    3. Add Created Text Node as the last child node just created Li element
    4. Add newly created Li node as the last child element unit UL
    // Create an element (node) Li Var Elementli \u003d document.createElement ("Li"); // Create a text node containing the text "Smartphone" var textsmart \u003d document.createtextNode ("CMaptfon"); // add the created text node as the last child element to the newly created element Li Elementli.appendchild (TextSmart); // Get the item to which the created Li node will be added as a child elementul \u003d document.getelementByid ("List"); // Add the created element Li as the last child element to UL with id \u003d "List" elementul.appendchild (Elementli);

    APPENDCHILD () and INSERTBEFORE () methods when working with existing nodes

    Working with existing nodes by AppendChild () and InsertBefore () methods is also carried out in 2 stages:

    1. Get an existing knot in the tree.
    2. Specify the place where you want to insert a node using the AppendChild () or InsertBefore () method. In this case, the node will be removed from the previous place.

    For example, add an existing LI element containing the text "Tablet" to the top of the list (in this case it will be removed from the previous place):

    // Get an UL element containing a list by its ID VAR Elementul \u003d Document.getelementByid ("List"); // Get an element LI containing a text node "Tablet" var elementli \u003d elementul.childnodes; // add an item to the top of the list // In this case, it will be removed from the source place Elementul.insertBefore (Elementli, elementul.firstchild);

    The task

    • There are two list in the document. It is necessary to move items from the second list to the first.
    • Create a list, text field and 2 buttons. Write code in the JavaScript language, which, depending on the pressed button, adds the text located in the text box, to the beginning or to the end of the list.

    Removing nodes

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

    1. Get (Find) This node in the tree. This action is usually carried out in one of the following methods: GetElementByid (), GetElementsByClassName (), GetElementsByTagname (), GetElementsByName (), QuerySelector () or QuerySelectorall ().
    2. Call the Removechild () method from the parent node to which the node we want to remove it as a parameter.
      The removechild () method returns a remote node or NULL as the value if the node that we wanted to delete did not exist.

    // Find the node that we want to remove VAR Findelement \u003d Document.getelementByid ("Notebook"); // Call the Removechild // from the parent node and transfer it to the Findelement.ParentNode.Removechild (Findelement) as a parameter;

    For example, delete the last child element at an item having id \u003d "MyId":

    // Get an item with ID \u003d "MyId" var MyId \u003d Document.getelementByid ("MyId"); // Get the last child node at the MYID VAR Lastnode \u003d MyId.lastchild element; //t.k. We do not know whether the last child element element is element, // then use the WHILE cycle to search for the last child element at the MyId element // While the element has a node and its type is not equal to 1 (i.e. it is not an item) (LastNode && Lastnode.nodeType! \u003d 1) (// Go to the previous node LastNode \u003d Lastnode.PreviousSibling;) // If the MyId node, we found an IF element (LastNode) (// then it must be removed LastNode.ParentNode.Removechild ( LastNode);)

    For example, delete all subsidiary nodes at an item having id \u003d "MyQuestion":

    // Get an item from which we want to delete all its VAR ELEMENTQUESTION \u003d Document.getelementByid ("MyQuestion"); // While there is the first WHILE element (ElementQuestion.firstelement) (// Delete it elementquestion.Removechild (element.firstchild);)

    The task

    1. Write a function that removes all text nodes at the item.
    2. There are 2 list (), write the code in the JavaScript language, removing all the items from 1 and 2 list.
  • If I had to write JavaScript ever and had to write something like a javascript:
    var p \u003d document.createElement ("P");
    P.APPENDCHILD (Document.CreateTextNode ("Real Fish Fish."));
    var div \u003d document.createelement ("DIV");
    div.setattribute ("ID", "NEW");
    div.appendchild (P);

    it can be useful to you.

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

    I propose a simple task solutions tool - the CREATE () function (source below). For example, creating a text paragraph:
    var el \u003d create ("P", (), "Farewell, Love!");

    Or DIV with paragraph and reference inside it:
    var div \u003d create ("DIV", (ID: "NEW", STYLE: "Background: #FFF"),
    Create ("P", (Align: "Center"),
    "introduction: ",
    Create ("A", (href: "ua.fishki.net/picso/kotdavinchi.jpg"),
    "picture"),
    ": end")
    );

    Or, we make the table:
    var holder \u003d document.getelementByid ("Holder2");
    var table;
    VAR TD;
    Holder.Apandchild (
    Table \u003d.
    Create ("Table", (ID: "UGLY", COLS: 3),
    CREATE ("TBODY", (),
    Create ("TR", (),
    Create ("TD", (width: "10%"),
    "Hello"),
    TD \u003d.
    Create ("TD", (Style: "Background: #FCC"),
    "THERE"),
    Create ("TD", (Class: "Special2"), "Everywhere")
    )
    );

    Note:

    1. IE requires a TBODY item, otherwise refuses to show the table.
    2. Class Attribute with something conflicted, so you have to write it as Class. It seems that the result does not affect the result.
    3. Table \u003d and TR \u003d In the example, it allows you to save the created attached objects for further work with them.
    4. This code works in IE, and in Mozilla, and in Opera.

    Function itself

    fUNCTION CREATE (NAME, ATTRIBUTS) (
    var el \u003d document.createElement (name);
    if (Typeof attributes \u003d\u003d "Object") (
    For (Var i in attributes) (
    el.setattribute (i, attributes [i]);

    If (i.TolowerCase () \u003d\u003d "Class") (
    el.classname \u003d attributes [i]; // for ie compatibility

    ) ELSE if (i.TolowerCase () \u003d\u003d "Style") (
    el.style.cstext \u003d attributes [i]; // for ie compatibility
    }
    }
    }
    for (var i \u003d 2; i< arguments.length; i++) {
    var val \u003d arguments [i];
    if (Typeof Val \u003d\u003d "String") (VAL \u003d Document.CreateTextNode (VAL));
    el.appendchild (VAL);
    }
    Return EL;
    }


    Behind the idea should be thanked Ivan Kurmanova,
    Original article with working examples:

    Last updated: 1.11.2015

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

      createEelement (ElementName): Creates an HTML element, the tag of which is transmitted as a parameter. Returns the created item

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

    var elem \u003d document.createElement ("div"); var elemtext \u003d document.createtextNode ("Hi Mir");

    Thus, the ELEM variable will store the link to the DIV element. However, one creating elements is not enough, they still need to add to the web page.

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

      aPPENDCHILD (NewNode): Adds new NEWNODE node to the end of the collection of subsidiaries

      iNSERTBEFORE (Newnode, ReferenceNode): adds new newnode node in front of the ReferenCenode node

    We use the AppendChild method:

    Title Articles

    First paragraph

    Second paragraph



    First create an ordinary H2 header element and a text node. Then the text node is added to the header element. Then add the title to one of the web page items:

    However, we are not necessary to define text inside the element create an additional text node, since we can use the TextContent property and directly assign text:

    Var elem \u003d document.createElement ("H2"); elem.textContent \u003d "Hello Mir";

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

    Now consider how the similar element add to the beginning of the collection of child nodes of the divorce Div:

    Var ArticleDiv \u003d Document.QuerySelector ("Div.article"); // Create a VAR Elem \u003d Document.createElement element ("H2"); // Create a VAR Elemtext \u003d Document.CreateTextNode for it ("Hi Mir"); // add text to the element as the element element elem.appendchild (Elemtext); // Get the first element in front of which will be adding Var Firstelem \u003d articlediv.firstchild.nextsibling; // Add an item to block DIV in front of the first article ArticleDiv.insertBefore (Elem, Firstelem);

    If we need to insert a new node on the second, third or any other place, then we need to find a node that you need to insert, using the combinations of FirstChild / Lastchild and NextSibling / Previoussibling properties.

    Copying element

    Sometimes items are quite complex in composition, and it is much easier to copy them than using individual calls to create from content. To copy already existing nodes, the Node object can use the CloneNode () method:

    Var ArticleDiv \u003d Document.QuerySelector ("Div.article"); // Cloning the article ArticleDiv Var NewArticleDiv \u003d ArticleDiv.cloneNode (TRUE); // Add to the end of the Body Document.body.appendchild element (NewArtICLEDIV);

    In the CloneNode () method, a logical value is transmitted as a parameter: if TRUE is transmitted, the item will be copied with all the subsidiaries; If False is transmitted - it is copied without subsidiaries. That is, in this case, we copy the node with all its contents and then add the Body element to the end.

    Removing item

    To remove the item, the removchild () object () object of the Node object is called. This method removes one of the subsidiaries:

    Var ArticleDiv \u003d Document.QuerySelector ("Div.article"); // Find a node that we will delete - the first paragraph var removablenode \u003d document.queryselectorall ("Div.article P"); // Delete the ARTICLEDIV.REMOVECHILD node (RemovableNode);

    In this case, the first paragraph from the div is deleted

    Replacing element

    To replace the item, the method is used replacechild (Newnode, OldNode) Node object. This method takes a new element as the first parameter that replaces the old OLDNode element transmitted as the second parameter.

    Var ArticleDiv \u003d Document.QuerySelector ("Div.article"); // Find a node that we will replace - the first paragraph var oldnode \u003d document.queryselectorlall ("Div.article P"); // Create a Var Newnode \u003d Document.CreateElement element ("H2"); // Create a VAR Elemtext \u003d Document.CreateTextNode for it ("Hi Mir"); // add text to the item as a newnode.appendchild (Elemtext); // Replace the old node of the new articleDiv.replacechild (Newnode, OldNode);

    In this case, we replace the first paragraph heading H2.

    This is the fourth part of the posts dedicated to the native equivalents of jQuery methods. You can read and before continue.

    In this article, we will consider ways to create, insert, move and remove elements. And although jQuery already contains a large number of useful methods, you will be surprised when you find out that all this can be easily done using native methods.

    Manipulation with HTML code of elements

    jQuery.
    // Get Var HTML \u003d $ (ELEM) .html (); // SET $ (ELEM) .html ("
    New HTML.
    ");
    Native JS.
    // Get Var HTML \u003d Elem.innerhtml; // set elem.innerhtml \u003d "
    New HTML.
    ";

    Manipulation with text elements

    jQuery.
    // Get Var Text \u003d $ (Elem) .text (); // SET $ (ELEM) .text ("New Text");
    Native JS.
    // Get Var Text \u003d Elem.TextContent; // Set Elem.TextContent \u003d "New Text";

    Creating an item

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

    Adds content to end elements

    jQuery.
    $ (parentnode) .append (newnode);
    Native JS.
    parentnode.appendchild (newnode);

    Adds content to the beginning of the elements

    jQuery.
    $ (ReferenCenode) .Prepend (Newnode);
    Native JS.
    referencenode.insertBefore (newnode, referencenode.firstelementchild); // or referencenode.insertadjacentelement ("Afterbegin", NewNode); // FF 48.0+, IE8 +

    Insert immediately before 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 the INSERT Directly After An Element 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 referencenode is located in the DOM tree and has a parent element.

    Look at the following:

    Referencenode.insertadjacentelement (Position, Node);

    The insertadjacentElement method accepts two parameters:

    • position - Position relative to referencenode, should be one of the following:
      • 'Beforebegin' - in front of the element itself.
      • 'Afterbegin' - inside the element, before the first descendant.
      • 'Beforeend' - inside the element, after the last descendant.
      • 'Afterend' - after the element itself.
    • node - knot for insertion
    Text Content

    Some Text
    Some Text
    var elem1 \u003d document.getelementbyid ("Elem1"); var elem2 \u003d document.getelementByid ("Elem2"); elem1.insertadjacentelement ("Beforeend", Elem2); // Result
    Some Text
    Some Text

    Insertadjacencelement method is more understandable and intuitive than insertbefore method, but the latter is better supported in old browsers.

    Multiple addition of elements

    It is also worth noting that adding an item to the node that is in the DOM tree will lead to redrawing. It 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 descendants of the element, ancestors and elements that will appear after it in the DOM. If you add many items to DOM, it may take some time.

    What to avoid this, you can add to the DocumentFragment. A fragment of the document is a Document object that exists only in memory, so adding to it will not cause any recompositions.

    Suppose 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 \u003d Document.QuerySelector ("UL"); // Make 100 List Elements for (var i \u003d 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 that is in the DOM tree, therefore, will drive to the redraw on each iteration - it is 100 changes!

    Let's find the best way.

    // Get The Element That Will Contain Our Items Var Ul \u003d Document.QuerySelector ("UL"); // CREATE A Document Fragment to Append The List Elements to Var DocFrag \u003d document.createdocumentFragment (); // Make 100 List Elements for (var i \u003d 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 document fragment in memory, so that the recomposing will work when the fragment is added to the UL element. This method will reduce the number of redraws from 100 to 1.

    Removing item

    jQuery.
    $ (ReferenCenode) .Remove ();
    Native JS.
    referencenode.parentnode.removechild (ReferenteNe); // or referencenode.remove (); // FF 23.0+, 23.0+, Edge (No Ie Support)