DOM Basics

DOMTree

The node type

Nodes: Everything contained in a document is a node node

How to get a node

Describe and obtain the properties of the relationship between nodes: given a node, any node associated with it can be obtained based on these properties

childNodes

Grammar: [container].childnodes

Meaning: Get all child nodes

Note: Contains various types

Get content: the collection NodeList

children

Grammar: [container]. Children

Meaning: Gets all the child nodes of the current element

Note: This is a collection of elements, with only element nodes

Get content: Collection HTMLCollection

parentNode

Grammar: [node]. ParentNode

Meaning: Gets its unique parent node

previousSibling

Grammar: [node]. PreviousSibling

Meaning: Get its elder node

Note: Get only one, the one next to it, and not necessarily the element node

previousElementSibling

Grammar: [node]. PreviousElementSibling

Meaning: Gets its element sibling node

Note: Not compatible with lower versions of Internet Explorer

nextSibling

Grammar: [container]. NextSibling

Meaning: Get its younger brother node

Note: Get only one, the one next to it, and not necessarily the element node

nextElementSibling

Grammar: [container]. NextElementSibling

Meaning: Gets its element sibling node

Note: Not compatible with lower versions of IE

firstChild

Grammar: [container]. FirstChild

Meaning: Get the first {eldest} of all its children

firstElementChild

Grammar: [container]. FirstElementChild

Meaning: Gets the first of all of its element child nodes

lastChild

Grammar: [container]. LastChild

Meaning: Get the last {youngest child} of all its children

lastElementChild

Grammar: [container]. LastElementChild

Meaning: Gets the last {youngest child} of all element children.

If you can’t find what you want, the result is null

Add, delete and modify nodes

Add to the page specified container

  • Container. AppendChild puts the element object at the end of the container
Insert A{new} before B{existing} (b.parentNode).insertbefore (A,B)Copy the code

Dynamically create an element node (element tag)

var link = document.createElement('a'); link.href = 'http://www.zhufengpeixun.cn'; Link. innerHTML = 'Everest Training ';Copy the code

Dynamically create a text node

Var text = document.createTextNode(' I am the content of the text ');Copy the code

Remove nodes

box.parentNode.removeChild(box);
Copy the code

cloning

Var box2 = box.cloneNode(true); // node. cloneNode(false/true) clone the current node. document.body.appendChild(box2);Copy the code