Dom manipulation of JavaScript

Source: Internet
Author: User
Tags tag name

First, document.getElementById () Gets the element node by ID

    <div id= "Div1" >        <p id= "P1" >            I was the first p</p> <p        id= "P2" >            I was the second p</p>    </div>        window.onload = function () {            var str = document.getElementById ("P1"). InnerHTML;            alert (str);        Pop Up    I'm the first P        }


Second, Document.getelementsbyname () Gets the element node according to the name

    <div id= "Div1" >        <p id= "P1" >            I was the first p</p> <p        id= "P2" >            I was the second p</p>        <input type= "text" value= "Please enter value" name= "UserName"/>        <input type= "button" value= "OK" onclick= "fun1 ()" >    </div>                function fun1 () {            var username = document.getelementsbyname ("username") [0].value;            Alert (username);    Output value entered in username        }


document.getElementsByTagName () Gets the element node according to the HTML tag name, note that the getelements*** selector returns a NodeList object, which can traverse the output by selecting 1 of them according to the index number.

    <div id= "Div1" >        <p id= "P1" >            I was the first p</p> <p        id= "P2" >            I was the second p</p>    </div>    window.onload = function () {            var str = document.getelementsbytagname ("P") [1].innerhtml;            alert (str);        Output  I am the second p, because I get the index of 1 p, index starting from 0        }        window.onload = function () {            var arr = document.getElementsByTagName ("P");            for (var i = 0; i < arr.length; i++) {                alert (arr[i].innerhtml);            }        }    Window.onload = function () {            var node = document.getElementById ("Div1");         var Node1 = document.getElementsByTagName ("P") [1];    Get alert (node1.innerhtml) from the acquired element again            ;    }


Iv. Document.getelementsbyclassname () Gets the element node based on class

    <div id= "Div1" >        <p id= "P1" class= "Class1" >            I am the first p</p> <p id=        "P2" >            I am the second P </p>    </div>    window.onload = function () {            var node = document.getelementsbyclassname ("Class1" ) [0];            alert (node.innerhtml);        }

V. CSS selectors in JavaScript

    Document.queryselector ()    ///based on the rules of the CSS selector, returns the first match to the element    Document.queryselectorall ()    ///According to the rules of the CSS selector, Returns all matching elements    <div id= "Div1" >        <p id= "P1" class= "Class1" >            I was the first p</p> <p        id= "P2" class= "Class2" >            I am the second p</p>    </div>        window.onload = function () {            var node = Document.queryselector ("#div1 > P");                alert (node.innerhtml);                Output  I am the first P            var node1 = Document.queryselector (". Class2");            alert (node1.innerhtml);                Output  I am the second P            var nodelist = Document.queryselectorall ("P");            Alert (nodelist[0].innerhtml + "-" + nodelist[1].innerhtml);    Output  I am the first P-I am the second P        }


VI. Document structure and traversal
(1) As the number of nodes of the document
1. ParentNode Gets the parent node of the node
2, ChildNodes Gets the node's child node array
3. FirstChild Gets the first child node of the node
4. LastChild Gets the last child node of the node
5. NextSibling gets the next sibling element of the node
6. Previourssibling gets the previous sibling element of the node
7, the type of the NodeType node, 9 for the document node, 1 for the element node, 3 for the text node, 8 for the comment node, and 11 for the DocumentFragment node
8. Text content of Nodevlue text node or comment node
9. The tag name of the NodeName element (such as P,span, #text (text node), DIV), denoted in uppercase

Note that the above 6 methods even element nodes are counted as one node.

<div id= "Div1" > <p id= "P1" class= "Class1" > I was the first p</p> <p id=            "P2" class= "Class2" > I am the second p</p> </div> window.onload = function () {            var Node1 = Document.queryselector (". Class2"); alert (Node1.parentNode.innerHTML); Output <p id= "P1" class= "Class1" > I was the first p</p><p id= "P2" class= "Class2" > I was the second p</p> var node            List = document.getElementById ("Div1");            var arr = nodelist.childnodes; Alert (arr[1].innerhtml + "-" + arr[3].innerhtml); Output I am the first P-I am the second p why is 1,3? Because the text node of this method is also fetched,
That is, 0,2,4 is a text node} <div id= "Div1" > Text 1 <p id= "P1" class= "Class1" > I am the first p</p> text 2 <p id= "P2" class= "Class2" > I am the second p</p> text 3 </div> window.onload = function () {//output, Text 1, I am the first p, text 2, I am the second p, text 3 var node = Docum Ent.getelementbyid ("Div1"); for (var i = 0; i < node.childNodes.length; i++) {if (Node.childnodes[i].nodetype = = 1) { alert (node.childnodes[i].innerhtml); } else if (Node.childnodes[i].nodetype = = 3) {alert (node.childnodes[i].nodevalue); } } }

(2) document as an element tree
1. Firstelementchild the first child element node
2. Lastelementchild the last child element node
3. Nextelementsibling Next sibling element node
4, previouselementsibling before a sibling element node
5, Childelementcount number of child element nodes
Note that this 5 method text node is not counted in

        <div id= "Div1" >            <p id= "P1" class= "Class1" >                I am the first p</p> <p id=            "P2" class= "Class2" >                I am the second p</p>      </div>        window.onload = function () {            var node = document.getElementById (" Div1 ");            var node1 = Node.firstelementchild;            var node2 = Node.lastelementchild;            alert (node.childelementcount);  Output 2,DIV1 There are altogether two non-text element node            alert (node1.innerhtml);         Output I am the first P            alert (node2.innerhtml);         Output I am the second P            alert (Node2.previousElementSibling.innerHTML);  Output I am the first P (the last non-text element node of the second element node is P1)            alert (Node1.nextElementSibling.innerHTML);      Output I am the second P (the next sibling of the first element node is a non-text node is P2)        }


Vii. JavaScript manipulating HTML properties
1, the properties of the read, it is important to note that some HTML attribute names in JavaScript is reserved words, so there will be a little different, such as class,lable in the for in JavaScript into Htmlfor,classname.

    <div id= "Div1" >            <p id= "P1" class= "Class1" > I am the first p</p>             <input type= "text" value= "I am a text box" id= "input1"/>        </div>        window.onload = function () {            var nodetext = document.getElementById ("input1");            alert (nodetext.value);        Output I am a text box            var nodeimg = document.getElementById ("Img1");            alert (nodeimg.alt);            Output I am a picture            var nodep = document.getElementById ("P1");            alert (nodep.classname);        Output Class1    note Get class is classname, if written nodep.class output undefined        }

2, the setting of the property, the same thing to note here is the reserved word

    <div id= "Div1" >                    </div>    function fun1 () {            document.getElementById ("img1"). src = "1small.jpg";        Change the Path property of the picture. The effect of the implementation is that when you click on the picture, the large map becomes smaller.        }


3. Non-standard HTML attributes
GetAttribute (); Note that these two methods do not have to ignore the javascript reserved words, the HTML attribute is what to write.
SetAttribute ();

        <div id= "Div1" >                    </div>    function fun1 () {            document.getElementById ("Img1"). SetAttribute ("src", "1small.jpg");            Alert (document.getElementById ("Img1"). GetAttribute ("class"));        }

4. Properties of the attr node
The Attributes property of a non-element object returns null,element half of the returned Attr object. The Attr object is a special node that gets the property name and value by name and value.
such as: document.getElementById ("IMG1") [0];
document.getElementById ("Img1"). Src;

    <div id= "Div1" >                    </div>    function fun1 () {            alert (document.getElementById ("Img1"). Attributes[0].name);    Output  onclick    Note that access via indexer is written on the right side in front of the row, starting from 0            alert (document.getElementById ("Img1"). Attributes.src.value);    Output 1big.jpg            document.getElementById ("Img1"). Attributes.src.value = "1small.jpg";    Click to change the SRC attribute, to achieve a click on the large image to small image effect        }


Viii. content of elements
1, InnerText, textcontent innerText and textcontent difference, when the text is empty, InnerText is "", and textcontent is undefined
2, InnerHTML

    <div id= "Div1" >            <p id= "P1" > I am the first p</p> <p            id= "P2" > I am the <b> two </b> p</p >        </div>        window.onload = function () {            alert (document.getElementById ("P1"). InnerText);  Note The Firefox browser does not support innertext            alert (document.getElementById ("P1"). textcontent);    Basic support for Textcontent            document.getElementById ("P1"). textcontent = "I am p1,javascript changed me";    Sets the document Text            alert (document.getElementById ("P2"). textcontent);            Alert (document.getElementById ("P2"). InnerHTML); The difference between innerHTML and innertext is that the output of HTML code does not output HTML code        }


Nine, create, insert, delete node
1. document.createTextNode () Create a text node

        <div id= "Div1" >            <p id= "P1" > I was the first p</p> <p            id= "P2" > I was the second p</p>        </div >    window.onload = function () {            var textnode = document.createTextNode ("<p> I am a new JavaScript node </p > ");            document.getElementById ("Div1"). AppendChild (Textnode);        }


When finished, the HTML becomes:
Div id= "Div1" >
<p id= "P1" > I was the first p</p>
<p id= "P2" > I am the second p</p>
I am a new JavaScript node
</div>

2, Document.createelement () Create an element node

    <div id= "Div1" >            <p id= "P1" > I was the first p</p> <p            id= "P2" > I was the second p</p>        </div >    window.onload = function () {            var pnode = document.createelement ("P");            Pnode.textcontent = "Create a new P-node";            document.getElementById ("Div1"). AppendChild (Pnode);        }

After execution, the HTML code becomes:

<div id= "Div1" >
<p id= "P1" > I was the first p</p>
<p id= "P2" > I am the second p</p>
<p> Create a new P node </p>
</div>

3. Inserting nodes
AppendChild ()//Inserts a node into the last face of the calling node
InsertBefore ()//accepts two parameters, the first is the node to be inserted, the second indicates which node precedes it, and if it does not pass in the second argument, it is the same as appendchild and is placed last.

    <div id= "Div1" >            <p id= "P1" > I am the first p</p>        </div>    window.onload = function () {            var pNode1 = document.createelement ("P");            Pnode1.textcontent = "InsertBefore inserted node";            var pNode2 = document.createelement ("P");            Pnode2.textcontent = "AppendChild inserted node";            document.getElementById ("Div1"). AppendChild (PNode2);            document.getElementById ("Div1"). InsertBefore (Pnode1,document.getelementbyid ("P1"));        }

After execution, the HTML code is:
<div id= "Div1" >
<p>insertbefore inserted Nodes </p>
<p id= "P1" > I was the first p</p>
<p>appendchild inserted Nodes </p>
</div>

Ten, delete and replace nodes.
1, removechild (); Called by the parent element to delete a child node. Note that the immediate parent element is called, and deleting the immediate child element is effective, and deleting the grandson element has no effect.

    <div id= "Div1" >            <p id= "P1" > I was the first p</p> <p            id= "P2" > I was the second p</p>        </div >    window.onload = function () {            var div1 = document.getElementById ("Div1");            Div1.removechild (document.getElementById ("P2"));        }


After execution, the code becomes:
<div id= "Div1" >
<p id= "P1" > I was the first p</p>//notice that the second P element has been removed
</div>

2, ReplaceChild ()//delete a child node, and replace it with a new node, the first parameter is the new node, the second node is the replaced node

    <div id= "Div1" >            <p id= "P1" > I was the first p</p> <p            id= "P2" > I was the second p</p>        </div >    window.onload = function () {            var div1 = document.getElementById ("Div1");            var span1 = document.createelement ("span");            Span1.textcontent = "I am a new span";            Div1.replacechild (Span1,document.getelementbyid ("P2"));        }

After execution completes, the HTML code becomes:
<div id= "Div1" >
<p id= "P1" > I was the first p</p>
<span> I am a new span</span>//notice that the P2 node has been replaced with the Span1 node
</div>

Xi. JavaScript manipulation element CSS

The element's style property allows you to freely read and set the element's CSS style, as an example:

 

Reprint: http://www.cnblogs.com/kissdodog/archive/2012/12/25/2833213.html

Dom manipulation of JavaScript

Related Article

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.