Add a new element to the Dom -- adding elements to the DOM

Source: Internet
Author: User

Adding new DOM elements to a document is sometimes necessary. Like shutting down an elephant in the refrigerator, there are three steps in total:

  1. Step 1: Create a node or element you want to add)
  2. Step 2: let Dom know where you want to add it to the document, that is, use document. getelementbyid () or parent to locate the parent element position in the document tree.
  3. Step 3: add the newly created node or element to the location you want to add. Use methods such as appendchild () and insertbefore ().

Node nodes can be represented as text, tag tags, or attributes of a DOM object, which will be involved in this tutorial.

Create a node element:

You can easily create a node by calling the Document Object method. We use the createtextnode () method of the Document Object. Document. createtextnode (text content) returns a node containing the corresponding text content ):

VaR txtnode = Document. createtextnode ("Hello. This is a new node .");

The createelement () method of the Document Object can easily create a DOM Element Object. The setattribute () method of the object can be used to assign values to attributes of the element object. Suppose you want to create a tag and assign values to its href attribute, you can do this:

Ar link = Document. createelement ('A ');
Link. setattribute ('href ', 'mypage.htm ');

Example will create a superlink and point it to mypage.htm (<a href?”mypage.htm "> ). You can create any tag. Here I create a hyperlink because it is very simple, isn't it? You can also assign values to any attribute you want to set, not just the href attribute. If you want to add a name attribute for it, you can use the following statement:

Link. setattribute ('name', 'myanchor ');

Now you have created this node, but you cannot see it, because you have not put it in the document. We will introduce its operation process later.

Locate the placement of new elements or nodes:

Once you have successfully created a node you want, you must find the location where you want to add it to the document tree. Document tree represents all labels, attributes, and text content in the Document Object Model. To locate the location where we want to add our new node in the document tree, we have two methods:

  1. Add an ID attribute for the element located in the document tree.
  2. Use the father and child in the tree structure to write and locate

Use Id to locate the location we have selected for our new node in the document tree. We can use document. getelementbyid (). this will return the DOM object containing the given ID (it can be div, P, span, and so on ). For example, to obtain a div object whose ID is mydiv, we use the following syntax:

Document. getelementbyid ("mydiv ");

If you want to use the hierarchical structure of the document to locate the tag location in the document tree, you must be familiar with the concepts of parent and child. If a node is in the content of another node, it is considered as the child of the outer node element. If a node has multiple adjacent nodes, the node is the father of all the nodes in it. For example, in a valid HTML file, except for HTML tags, other tags have parent nodes because they are all placed in HTML tags (). In most HTML documents, the body node has many children, because at least a piece of text is put in it.

The form of a document tree is as follows:

Document Tree

 

Use the level structure of parent and child to locate DOM objects. You can use document. childnodes [], document. nextsibling [], and document. parentnode []. For example, the structure of an HTML document is as follows:

<HTML>
<Head>
<Title> my document </title>
</Head>
<Body bgcolor = "red">
<Div id = "mydiv">
</Div>
</Body>
</Html>

We can locate the DIV tag whose ID is mydiv through the following steps: first, we find the second child (Body Tag) of the HTML tag ), what we are looking for is actually the first child of the Body Tag.

Document. childnodes [1]. childnodes [0];

We can also find this element in another way: First, we find the first child (Head tag) of the HTML tag, and then find the brother (Body Tag) of the head tag ), then find the first child of the body.

Document. childnodes [0]. nextsibling. childnodes [0];

Maybe you will ask, in the first example, why do we use childnodes [1] to describe their second child? Isn't it the first? That's because in Javascript, the attribute value starts with 0, 0 represents their first child node, 1 represents the second, and so on.

Place the newly added nodes and elements in the specified position:

Now, the new node has been created and its attaching position has been determined. In the last step, we should add it to the position of the located element. If you want to add a text node to an element with the ID of "mydiv", you can use the following statement:

// First, we create a node and assign it to a variable named TXT.
VaR TXT = Document. createtextnode ("this text was added to the Div .");
// First locate the element whose ID is mydiv and add a new text node to it
Document. getelementbyid ('mydiv '). appendchild (txt );

In the appendchild () method, you can not only place text nodes, but also other nodes. We only use text nodes to show how easy these operations are when you understand these methods. In the second line of code, we added a piece of text to the div. Next we use another method to add a new text to the end of the DIV:

<SCRIPT type = "text/JavaScript">
Function addtext (what ){
If (document. createtextnode ){
VaR mytext = Document. createtextnode (what)
Document. getelementbyid ("mydiv"). appendchild (mytext)
}
}
</SCRIPT> <Div id = "mydiv" onclick = "addtext ('this text was added to the div. ') "style =" Font: 20px bold; cursor: Hand ">
Click here for example
</Div>

In the above example, we use the appendchild () method to add a new text to the div. It adds the new text to the end of the DIV, that is, the closure of the DIV tag (</div> ). If we need to add it to the beginning of the DIV tag, we can do this:

Insertbefore (txt, document. getelementbyid ('mydiv '). firstchild );

This adds a text node at the beginning of the DIV label. The second parameter is the element before which the new node is to be added. In this example, we use the first subnode of the Div node, which means that the new text node is before the first subnode Of The DIV, that is, at the beginning of the div.

Not limited to Div and text nodes, because you can add any node to any position in the document.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.