Table of Contents
属性相关
元素创建以及增删改查
class相关
style相关
元素大小属性
坐标相关
Home Web Front-end JS Tutorial Summary of related knowledge about Dom in JS

Summary of related knowledge about Dom in JS

Oct 26, 2018 pm 04:26 PM
javascript

The content of this article is a summary of relevant knowledge about Dom in JS. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Purpose

Used to record and summarize learned knowledge points in order to review the past and learn new things

Explanation

Write it this way to facilitate your own memory

Memory Click

Node related

Dom node acquisition

getElement (Id, ClassName, TagName) and querySelector (/All this is a static node collection, not real-time)
childNodes/firstChild/lastChild/nextSibling/previousSibling/parentNode gets all types of related nodes, not just element nodes
children/firstElmentChild/lastElmentChild/nextElmentSibling/previousElmentSibling/parentElment, gets only element-related nodes

Node tree

Summary of related knowledge about Dom in JS

The key point is:

HTMLBodyElement These are all constructors, and the terminal of the prototype chain is still Object.prototype

document.body.__proto__ === HTMLBodyElement.prototype  //true
document.documentElement.__proto__.__proto__ === HTMLBodyElement.prototype.__proto__  //true  
document.documentElement.__proto__.__proto__===HTMLElement.prototype  //true
Copy after login

nodeType

##Node.PROCESSING_INSTRUCTION_NODEE7A ProcessingInstruction for XML documents, such as declaration. Node.COMMENT_NODE8A comment nodeNode.DOCUMENT_NODE9Document NodeNode.DOCUMENT_TYPE_NODE10DocumentType node that describes the document type. For example, document type declaration. Node.DOCUMENT_FRAGMENT_NODE11A DocumentFragment node, code fragment node

innerHTML,outerHTML,textContent
elem.innerHTML:指的是elem中所有的childNodes,包括注释节点可利用elem.innerHTML += "xxx"进行累计全覆盖
elem.outerHTML:指的是elem中所有的childNodes以及elem自身包括注释节点
elem.textContent:指的是elem的childNodes中所有的文本节点,不包括注释节点

注意点:

对于文本内容例如:,innerHTML会进行转译> innerHTML会对内容中的标签进行转译为html相应节点

当script片段放入innerHTML中时不会执行,但是对于包含事件类型的脚本就存在注入风险

"<script>alert(&#39;I am John in an annoying alert!&#39;)</script>"; //无风险
"<img  src="/static/imghw/default1.png" data-src="https://img.php.cn//upload/image/609/508/163/1540542304653784.png" class="lazy" alt="Summary of related knowledge about Dom in JS" >";                          //有风险
Copy after login

所以对于纯文本建议使用textContent

outerHTML可以用来replace替换当前及自身的内容

nodeValue只有文本和注释节点才有值,否则输出null

属性相关

attributes
  元素属性的map集合,可通过for-of迭代遍历出name-value

hasAttribute/get/set/remove ==>检测是否存在属性/得到/设置/删除

elem.proName与elem.getAttribute(proName)基本一致,有个别不一致,例如input-value

let input = document.querySelector("input");
input.setAttribute("value", 3);            //行间样式显示3
input.value = 666;                         //页面内容显示666
console.log(input.getAttribute("value"));  //3
Copy after login

自定义属性

通过data-log-n = 1可以通过elem.dataset.logN获取属性

元素创建以及增删改查

元素节点创建let div = document.createElement('div');文本节点创建let textNode = document.createTextNode('Here I am');

简单补充一个表格的创建

let table = document.createElement("table"); //创建一个table元素节点
let tbody = document.createElement("tbody"); //创建一个tbody元素节点
tbody.insertRow(0); //创建一行
tbody.rows[0].insertCell(0); //创建一行第一列
tbody.rows[0].cells[0].append(document.createTextNode("(0,0)")); //补充其内容
tbody.rows[0].insertCell(1); //创建一行第二列
tbody.rows[0].cells[1].append(document.createTextNode("(0,1)"));
table.append(tbody);
div.append(table);
Copy after login

元素增删改查
 node.append()与node.prepend()都是在node内部添加,一个始终往队尾加一个往队首加
  node.before()与node.after(),一个加在node自身节点的上面,一个加在下面
 node.replace();自身节点替换成参数节点
  还有一个node.insertAdjacentHTML(where,html);where有4种值
 "beforebegin"与"afterbegin"在node开始位置的前或者后添加html
 "beforeend"与"afterend"在node结束位置的前或者后添加html
  elem.removeChild():删除子节点,还存在内存中通过变量可以读取
  node.remove():则彻底删除,不再内存中,不再能被读取

class相关

className将class的value以字符串形式返回

classList将class的value以类数组对象返回,提供了4种方法方便对class进行增删改查

elem.classList.add/remove("class"):增加和删除类
  elem.classList.toggle("class"): 如果类存在,则删除它,否则添加它
  elem.classList.contains("class"): 返回true/false,检查给定的类

style相关

通过style获取属性值必须是在行间样式中有填写的,否则空;elem.style.borderLeftWidth="100px"通过破折号"-"变成大写可以获取属性,必须带有px

重置样式:elem.style.borderLeftWidth="";利用空字符串浏览器会应用CSS类及其内置样式

完全重写样式:div.style.cssText="color: red !important;"或者div.setAttribute('style', 'color: red...')

一种有css关联的样式,而不局限与行间样式:getComputedStyle(element[, pseudo])

       <style>
        .box {
            width: 100px;
        }
        
        .a {
            font-size: 1em;
        }
        .a:after {
            content: "666";
            display: inline-block;
            width: 10px;
            height: 10px;
        }
    </style>


    <div>
        <div>213</div>
    </div>

    <script>
        let div = document.querySelector(".a");
        //let style = getComputedStyle(div,"after");   读取伪类元素
        //console.log(style.content);
        let style = getComputedStyle(div);
        console.log(style.left);     //auto
        console.log(style.fontSize); //16px
    </script>
Copy after login

返回结果与css样式关联,返回结果是经过计算的,例如16px,并且结果不一定是我们想要的例如auto
它还能读取伪类元素的样式属性,将第二个参数填写after;getComputedStyle(element, "after")

元素大小属性

Summary of related knowledge about Dom in JS

记住这张图基本搞定:
简单写写:offsetWidth:元素全尺寸=border+padding+content+滚动条宽度;clientWidth/Height:只考虑可见部分content+padding(不加滚动条);
顶部边框宽度:clientTop,左边边框宽度:clientLeft,但是当滚动条在左边时要加上其宽度=clientLeft
offsetParent来获取最近的CSS定位祖先。并offsetLeft/offsetTop提供相对于它左上角的x / y坐标。
属性scrollWidth/scrollHeight还包括滚出(隐藏)部分,例如没有水平滚动,scrollWidth等于clientWidth

大多数几何属性是只读的,但scrollLeft/scrollTop可以更改,浏览器将滚动元素。

scrollLeft/scrollTop - 元素的滚动部分的宽度/高度
  注意点:
  如果一个元素不能被滚动(例如,它没有溢出,或者这个元素有一个"non-scrollable"属性), scrollTop将被设置为0。
  设置scrollTop的值小于0,scrollTop 被设为0
  如果设置了超出这个容器可滚动的值, scrollTop 会被设为最大值.

Summary of related knowledge about Dom in JS

顺便提提如何是浏览器滚动条滚动:scrollTo(x,y)让滚动条到水平x,垂直y的位置;scrollBy(x,y)让滚动条每次以水平x,垂直y的距离滚动;
scrollIntoView():参数true默认值,滚到顶部,false滚到底部;document.body.style.overflow = "hidden"禁止滚动

整个文档的宽度/高度,带有滚动的部分

let scrollHeight = Math.max(
  document.body.scrollHeight, document.documentElement.scrollHeight,
  document.body.offsetHeight, document.documentElement.offsetHeight,
  document.body.clientHeight, document.documentElement.clientHeight
);
Copy after login

窗口大小

两种办法:document.documentElement.clientWidth/Height window.innerWidth/Height有细微区别当有滚动条时,前者不包括后者包括

坐标相关

获取元素相对窗口的坐标elem.getBoundingClientRect()返回的包换坐标的对象,左上顶点的(left,top)以及右下顶点的(right,bottom)
网页滚出窗口部分,有两种方式计算pageYOffset或者document.documentElement.scrollTop
因此我们可以计算元素相对与页面的位置

function getCoords(elem) {
  let box = elem.getBoundingClientRect();

  return {
    top: box.top + pageYOffset,
    left: box.left + pageXOffset
  };
}
Copy after login

Constant Value Description
Node.ELEMENT_NODE 1 Element node, element
Node.TEXT_NODE 3 Text node, textContent

The above is the detailed content of Summary of related knowledge about Dom in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles