DOM tree
HTML documents are the backbone of the label.
According to the document object model (DOM), each HTML tag is an object, the same text in the label is also an object. Therefore, these objects are available through JavaScript action
if there are spaces (like any character as) a document, then they will become the text nodes in the DOM, if we remove them, there will not be anything.
<head>
Before the spaces and line breaks are ignored
</body>
placed after something, then it will automatically move to the internal body, because the HTML specification requires that all content must be located within. So there is no space behind possible.
Then the browser typically does not display text in the empty text nodes at the beginning / end, the label will not be displayed between empty text nodes.
If the browser encounters malformed HTML, DOM is in the form will automatically fix it
like:
<html>
even if not in the document, the browser will automatically create it
Press DOM specification, must have a table <tbody>
, the unused table so <tbody>
automatically added when forming the DOM.
Other nodes:
Comments do not affect the visual representation, it is a rule that must be followed in any way - if there is something in HTML, then it must be in the DOM tree.
All HTML DOM content is part of
the comment is even a node <!DOCTYPE...>
is also a section
DOM always have 12 kinds of nodes
Traversing the DOM node
All operations are from the DOM document
object begins, this object is assigned to a variable, modify operation
The topmost node
DOM node tree can document
attribute use
nodes corresponding to the top <html>
and <html> = document.documentElement
which <body> = document.body
, <head> = document.head
docment.body
possibly null, if the script
script into the <head>
label types, then the script does not have access to document.body
, that is null
childNodes
childNodes
Provides access to a collection of all the child nodes of a node includes text, which appears to be a number, an array of class really just an iterative method does not therefore array of
all nodes are set Dom can not be replaced by a read-only assignment corresponding nodes
except node a small part, almost all of the DOM set in real time, which is the reaction of the real-time status DOM
do not have for...in
to traverse the DOM set, this method lists all its properties.
Note that this property can only access to the current script
node corresponding to the previous script
by elem.hasChildNodes()
whether it contains a child node to detect
parentNOde / siblingNode
By elem.parentNode
accessible parent of the current node
by elem.previousSibling/elem.nextSibling
the corresponding node access to / sibling nodes under
Access only element nodes
- children: just get the type as a child element node
- firstElementChild, lastElementChild: just get the first or last child element
- previousElementSibling, nextElementSibling: siblings
- parentElement: parent element
parentElement may be null, as it is the method returns to the parent element node and return parentNode any type of parent node, and thus,document.documentElement.parentElement === null
HTMLCollection (dynamic)
Find a child element by element if the child element is a collection will return HTMLCollection
an array of classes
let tb = documet.querySelector('table')
let tbs = tb.tBodies // HTMLCollection [tbody]
let trs =tbs.rows // HTMLCollection [tr,tr,tr,...]
let tr1 = trs[0]
tr1.sectionRowIndex //0 当前 tr 在集合中的位置
tr1.rowIndex // 1 当前 tr 在整张表中的 位置
let tds = tr1.cells // HTMLCollection [td,td,td,...]
td[0].cellIndex //0 当前 td 在父元素 tr节点 中的位置
NodeList (static)
By document
the method document.querySelectorAll
or elem.querySelectorAll
the collection element returns the acquired NodeList
class array
getElement*
method only through the document
object call
let divs = document.querySelectorAll('div') // NodeList(4) [div.Owen, div#modal, div.main, div]
document.getElementsByTagName('div')//HTMLCollection [div.Owen]
matches
elem.matches(css)
Will detect elem
matches to a given css selector, returns true or false
closest
elem.closest(css)
This method looks css selector to match the ancestors of HTML, including itself, and returns the first element found
contains
elem.catains(dom)
Dom determines whether progeny of elem, elem or equal, returns true or false
Node Properties
All nodes are inherited from the root EventTarget
- EventTarget: as a basis, so that all DOM nodes support event
- Node: DOM node as the basis, to provide the core functionality of the DOM tree:
parentNode
,nextSibling
,previousSibling
,ChildNodes
etc. (read-only getter); text nodesText
, element nodesElement
, comment nodesComment
are inherited from Node - Element: DOM element as base class. Provide element-level navigation:
nextElementSibling
,children
,getElement*
,querySelector
and so on, the browser only supports HTML, also supports XML, SVG, etc., corresponding to the base classHTMLElement
,XMLElement
,SVGElement
- HTMLElement: as the base class for all elements, various elements are inherited
innerHTML and outerHTML
- innerHTML: Gets or replace all the child nodes of the current node (current node is not included)
- outerHTML: Replace the current node
Document fragment DocumentFragment
Wrapper for storage node, the browser will not show the need to display the contents inside the wrapper by interpolation method
function creatEl(){
let frag = new DocumentFragment();
for (let i=1;i<4;i++) {
let li = document.createElement('li')
li.append(i)
frag.append(li)
}
return frag
}
ul.append(creatEl())
Class pattern modification and other operations
elem.className
Elements corresponding to the class name, separated by a space the plurality of categories
ul.className // "class1 class2 ..."
But also a elem.classList
target class name is accessible, it is present in an array type manner, while having add/remove/toggle/contains
other methods
ul.classList // DOMTokenList(2) ["333", "444", value: "333 444"]
ul.classList.add('class1')
ul.classList.remove('class1')
ul.classList.toggle('class1') // true 新增
ul.classList.toggle('class1') // false 去除
ul.classList.contains('class1') //false 是否包含
Usually we use style.*
a separate style attributes to be modified, if you want to adjust a variety of styles available cssText
, the style of this method will be a direct replacement for the previous
ul.style.cssText = `
color: red ;
background-color: skyblue;
width: 20px;
text-align: center;`
The style attribute is operated only for a style property values, property values can not be read css class
<style>
body {margin:20 auto;}
</style>
<script>
document.body.style.margin // ""
</script>
Then we need to use the getComputedStyle(el,[,pseudo])
method to obtain the corresponding value
if you do not pass the reference value or meaningless, all styles will return to the elements, its property values are resolved values, such as font-size:1em
the final values obtained may be parsed "16px"
let res = getComputedStyle(document.body)
res.marginTop // "20px"
res.margin // 谷歌 "20px 0px" 在火狐中为 "" 因此访问确切属性值须使用完整属性名
Gets the size and distance of the rolling elements
- offsetTop / Left: obtaining relative position provided with a property to absolute relative, the distance element fixed value or td, th, table, body of
- offsetWidth / Height: acquiring external width / height, comprising a border, padding, scrollbar (display: none or not the document itself, its value is 0 or null, which can determine whether the current element is hidden)
- clientTop / Left: acquiring distance of the inside and outside (the left scroll bar, scroll bar comprising width)
- clientWidth / Height: acquiring content viewable area width and height, i.e. no scrollbars and border
- scrollWidth / Height: acquiring all content (including hidden portion) width and height
- scrollTop / Left: get on / left part hidden from the elements, including the border, these two properties can be modified, other attributes can only read the
HTML file without the<!DOCTYPE HTML>
above-mentioned properties may be different, this is not a question of JavaScript , but it will affect JavaScript.
Scroll through the window
pageXOffset / pageYOffset: acquiring moving distance of the visible window value can not be set
The window can be scrolled through window.scrollBy, window.scrollTo, elem.scrollIntoView
scrollBy(x,y)
: Scroll relative to the current position (x, y) positionscrollTo(x,y)
: Scroll to the top left of the page relative to the document (x, y), location, similarscrollTop/scrollLeft
elem.scrollIntoView(truly)
: If it is true that the truly scroll to the top of the window of the current element, the top element is aligned with the top of the window, if truly is false, the current window is aligned with the bottom of the bottom element.
If the barred window can scroll style property overflow
valuehidden
coordinate
getBoundingClientRect () `method to obtain coordinates of the object with respect to the visual window
All the properties are the visible window to the left (X) and a top (Y) as the starting point
ul.getBoundingClientRect()
/*
DOMRect {
bottom: 829.59375 // 元素底部的Y坐标
height: 210 // 元素真实高度
left: 0 // 元素左边 X 坐标
right: 1903 // 元素右边 X 坐标
top: 619.59375 // 元素顶部 Y 坐标
width: 1903 // 元素自身真实宽度即不包含滚动条
x: 0
y: 619.59375
}
*/
document.elementFromPoint
document.elementFromPoint(x,y)
Returns the visible window coordinates (x, y), the topmost element
let elem = document.elementFromPoint(0,0) // <p>556666</p>
If x,y
the return is not within the normal range null,
Coordinates relative to the document, JS does not provide native standard method, write your own out:
function getDomCoords(el){
let {top,left} = el.getBoundingClientRect()
return {
top:top+ window.pageYOffset,
left:left+window.pageXOffest
}
}