1. Dom operation
Document: The entire HTML file is called a document
Element: All tags are element elements
Attribute: Attributes inside the tag
Text: Content in the middle of the label is text
Node:document, element, attribute, and text are collectively referred to as node nodes.
2. Document Object
Each HTML document that is loaded into the browser becomes the Document object
The following two methods are obtained and need to traverse!
There are two other methods that are important.
Create text node: document.createTextNode ()
Create element node: document.createelement ()
3. Element Object
All the tags in the HTML page we recognize are element elements.
The following common properties and methods are available on all HTML elements:
Element.appendchild () |
Adds a new child node to the element as the last child node. |
Element.firstchild |
Returns the first child node of an element. |
Element.getattribute () |
Returns the specified property value for the element node. |
Element.innerhtml |
Sets or returns the contents of an element. |
Element.insertbefore () |
Inserts a new node before the specified existing child node. |
Element.lastchild |
Returns the last child element of an element. |
Element.setattribute () |
Sets or changes the specified property to the specified value. |
Element.removechild () |
Removes a child node from the element. |
Element.replacechild () |
Replaces a child node in an element. |
4. Attribute Object
All the tags in the HTML page we recognize are attribute
5. Dom Exercises
Use the list in the page to show some cities (Chengdu, Xian, Dali), we want to click on a button to dynamically add the city.
1) Step Analysis:
First step: Event (onclick)
Step two: Get the UL element node
Step three: Create a text node for a city
Fourth step: Create an LI element node
Fifth Step: Add the text node to the LI element node.
Sixth step: Add a child node using the method AppendChild () in element
2) Specific code implementation: (Window.onload set the implicit name function)
1 <!DOCTYPE HTML>2 <HTML>3 <Head>4 <MetaCharSet= "UTF-8">5 <title>Adding cities dynamically</title>6 <Script>7 window.onload=function(){8 document.getElementById ("btn"). onclick=function(){9 //1. Get the UL element nodeTen varUlele=document.getElementById ("UL1"); One //2. Create a text node for a city A varTextnode=document.createTextNode ("Zhoushan");//Zhoushan - //3. Create an LI element node - varLiele=Document.createelement ("Li"); //<li></li> the //4. Add a text node to the LI element node - Liele.appendchild (Textnode); //<li> Zhoushan </li> - //5. Add Li to ul - Ulele.appendchild (liele); + } - } + </Script> A </Head> at <Body> - <inputtype= "button"value= "Add New City"ID= "BTN"/> - <ulID= "UL1"> - <Li>Chengdu</Li> - <Li>Xi'an</Li> - <Li>Dali</Li> in </ul> - </Body> to </HTML>
Run in Google Chrome, click the button to add a new city, the effect is as follows:
JavaScript Learning--dom Objects