Since HTML documents are parsed by the browser, it is a DOM tree. To change the structure of HTML, you need to operate the DOM through JavaScript.
Always remember that DOM is a tree structure. There are actually a few operations to operate a DOM node:
- Update: Updating the content of the DOM node is equivalent to updating the content of the HTML represented by the DOM node;
- Traversal: traverse the child nodes under the DOM node for further operations;
- Add: Adding a child node under this DOM node is equivalent to adding an HTML node dynamically;
- Delete: Deleting this node from HTML is equivalent to deleting the content of the DOM node and all the child nodes it contains.
Before operating a DOM node, we need to get this DOM node in various ways. The most commonly used method is()
and()
, and CSS selector()
。
Since IDs are unique in HTML documents,()
You can directly locate the unique DOM node.
()
and()
Always return a set of DOM nodes. To accurately select the DOM, you can position the parent node first and then select from the parent node to narrow the scope.
For example:
// Return the node with ID 'test':var test = ('test'); // First locate the node with ID 'test-table', and then return all internal tr nodes:var trs = ('test-table').getElementsByTagName('tr'); // First locate the node with ID 'test-div', and then return all nodes with red in its internal class:var reds = ('test-div').getElementsByClassName('red'); // Get all direct child nodes under node test:var cs = ; // Get the first and last child nodes under the node test:var first = ; var last = ;
The second method is to usequerySelector()
andquerySelectorAll()
, you need to understand the selector syntax, and then use conditions to obtain nodes, which is more convenient:
// Get the node with ID q1 through querySelector:var q1 = ('#q1'); // Get all nodes in the q1 node that meet the criteria through querySelectorAll:var ps = (' > p');
Note: Lower versions of IE < 8 do not supportquerySelector
andquerySelectorAll
. IE8 only has limited support.
Strictly speaking, our DOM node refers toElement
, but the DOM node is actuallyNode
, in HTML,Node
includeElement
、Comment
、CDATA_SECTION
Many kinds, as well as root nodesDocument
Type, however, most of the time we only care aboutElement
, that is, the actual control of the page structureNode
, other types ofNode
Just ignore it. Root nodeDocument
Already bound to global variablesdocument
。
practise
The following HTML structure:
JavaScript
Java
Python
Ruby
Swift
Scheme
Haskell
<!-- HTMLstructure --> <div > <div class="c-red"> <p >JavaScript</p> <p>Java</p> </div> <div class="c-red c-green"> <p>Python</p> <p>Ruby</p> <p>Swift</p> </div> <div class="c-green"> <p>Scheme</p> <p>Haskell</p> </div> </div>
Please select the node with the specified criteria:
// Select <p>JavaScript</p>:var js = ???; // Select <p>Python</p>, <p>Ruby</p>, <p>Swift</p>:var arr = ???; // Select <p>Haskell</p>:var haskell = ???;