3.1 Understanding the DOM
The Document Object Model DOM defines a standard way to access and manipulate HTML documents. The DOM renders an HTML document as a tree structure with elements, attributes, and text (the node tree).
Let's take a look at the following code:
To decompose the HTML code into a DOM node hierarchy diagram:
An HTML document can say a collection of nodes, three common DOM nodes:
1. ELEMENT nodes:
2. Text node: Content that is presented to the user, such as JavaScript, DOM, CSS, and so on in <li>...</li>.
3. Attribute node: element properties, such as the <a> tag's link property href= "http://www.imooc.com".
3.2 Getting elements by ID
Syntax : document.getElementById ("ID")
Result: null or [Object Htmlparagraphelement]
Note: The obtained element is an object, such as the element that you want to manipulate, and we want to pass its properties or methods.
3.3 InnerHTML Properties
The InnerHTML property is used to get or replace the contents of an HTML element.
Grammar:
Object.innerhtml
Attention:
1.Object is an element that gets an element object, such as a document.getElementById ("ID").
2. Note that writing, innerHTML is case-sensitive.
We get the <p> elements by id= "Con", and the contents of the elements are output and changed, the code is as follows:
Results:
3.4 Changing HTML Styles
Grammar:
Object.style.property=new style;
Note: object is the element that gets the element object, such as by document.getElementById ("id").
Basic attribute Table (property):
Note: This table is only a small subset of CSS style properties, and other styles can be set and modified by this method.
Take a look at the following code:
Change the style of the <p> element, change the color to red, change the font size to 20, change the background color to blue:
<p id= "Pcon" >hello world!</p>
<script>
var MyChar = document.getElementById ("Pcon");
Mychar.style.color= "Red";
Mychar.style.fontsize= "20";
Mychar.style.backgroundColor = "Blue";
</script>
Results:
3.5 Show and hide (Display properties)
The display and hidden effects are often seen in Web pages and can be set by the display property.
Grammar:
Object.style.display = value
Note: object is the element that gets the element object, such as by document.getElementById ("id").
Value:
Take a look at the following code:
3.6 Control class name (ClassName property)
The ClassName property sets or returns the class property of the element.
Grammar:
Object.classname = ClassName
Role:
1. Get the class attribute of an element
2. Specify a CSS style for an element within the page to change the appearance of the element
Take a look at the following code to get the class attribute of the <p> element and change the classname:
Results: