JS Inserts a new node

Source: Internet
Author: User

InsertBefore ()

Grammar:

InsertBefore (Newchild,refchild)

Newchild Inserting a new node

Refchild inserting a new node before this node

<ul id= "MyList" >

<li>Coffee</li>

<li>Tea</li>

</ul>

function MyFunction () {

var newitem=document.createelement ("LI")

var textnode=document.createtextnode ("Water")

Newitem.appendchild (Textnode)

var List=document.getelementbyid ("MyList")

List.insertbefore (Newitem,list.childnodes[0]);

}

AppendChild ()

Grammar:

AppendChild (newchild)

Newchild the nodes that are added

<ul id= "MyList" >

<li>Coffee</li>

<li>Tea</li>

</ul>

function MyFunction () {

var node=document.createelement ("LI");

var textnode=document.createtextnode ("Water");

Node.appendchild (Textnode);

document.getElementById ("MyList"). appendchild (node);

}

JS write basic InsertAfter () method

Dom does not provide a InsertAfter () method

function InsertAfter (newelement, targetelement) {

var parent = Targetelement.parentnode;

if (Parent.lastchild = = targetelement) {

If the last node is the target element, it is added directly. Because the default is the last

Parent.appendchild (newelement);

}else {

Parent.insertbefore (newelement, targetelement.nextsibling);

If it is not, it is inserted in front of the next sibling node of the target element. Which is behind the target element.

}

}

JS Inserts a new node

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.