search
HomeWeb Front-endJS TutorialDOM Basics of JavaScript Study Notes 2.4_javascript skills

The development of DOM is closely related to the general trend of WEB standardization. Only based on correct semantic logic can DOM function correctly. Nowadays, requirements such as correct semantic structure and separation of presentation and content have become basic requirements in web design. Therefore, in web front-end development, the existence of DOM undoubtedly provides an excellent API for connections at the presentation layer, behavior layer and even content level, and has become an indispensable part of popular Ajax applications.

1. Smooth degradation

1. Concept

In the early days, before JavaScript was used, the content in the web page could be displayed normally, and users could browse to relevant content through peripheral devices (such as a mouse). This browsing experience may not be ideal for users.

Based on this demand, content providers have a rational goal—that is, using JavaScript to improve user experience and increase user stickiness without affecting content display.

In this heading, there is a very obvious condition, which is that it cannot affect the normal display of the content. In other words, even if the user's browser does not support JavaScript, the user can still browse normally.

2. Method

①Separate JavaScript from HTML

This is the first thing that should be thought of. If the two are separated, HTML will be like returning to its early state before JavaScript was used, and it will be as smooth as ever.

For example, write event handling functions such as element.onClick into JavaScript and bind them to a certain function.

②Detect methods in JavaScript

Some of the methods mentioned before, such as getElementById, need to be determined whether the method is supported.

<script>
if(! document.getElementById) return false;
</script>

Use the if statement to detect whether the method is supported. If it is supported, you can continue. If it is not supported, it will return false directly. This way there is no need to waste time and it also plays a role in performance optimization.

2. Binding onload event

1. Reason for binding

Some functions need to be fully loaded before the page can be effectively executed. We need to bind the function to the window.onload event.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>筱雨生 - 博客园</title>
<script>
function tagAttribute(){
var ali = document.getElementsByTagName('li'); 
for(var i = 0; i < ali.length; i++){
  if(ali[i].firstChild.nodeType == 3){
    alert(ali[i].childNodes[0].nodeValue);
  }
}
}
window.onload = tagAttribute;
</script>
</head>
<body>
<h1 id="筱雨生">筱雨生</h1>
<p>時光飛逝,莫讓網絡蹉跎了歲月</p>
<div id="myBlog">
<ul>
<li title="JavaScript">JavaScript</li>
<li title="HTML">HTML</li>
<li title="CSS">CSS</li>
<li title="我的随笔">我的随笔</li>
<li></li>
</ul>
</div>
</body>
</html>

In the above example, if window.onload is not bound, executing the function tagAttribute will be meaningless.

Another thing to note is that the function is bound, not the value of the function, so there are no parentheses after it.

2. Binding method

If you only need to bind a function, then the above method can easily achieve your purpose.

window.onload = myFunction;

If there are multiple functions, you may bind them one by one. However, the result of this is that only the last function will be effectively executed. This is actually very easy to understand.

Our goal is that no matter how many functions are executed when the page is loaded, these functions can be executed effectively, that is, these functions are successfully bound to the window.onload event.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>筱雨生 - 博客园</title>
<script>
function addOnLoadEvent(func){
  var oldonload = window.onload; // 把现有的window.onload事件处理函数的值存储到变量oldonload
  if(typeof window.onload != 'function'){ // 如果这个处理函数上还没有绑定任何函数
    window.onload = func; // 将这个函数绑定到window.onload事件
  }else{
    window.onload = function(){ // 如果这个处理函数已经绑定了函数,就把这个函数追加到指令的末尾
      oldonload();
      func();
    }
}
}
//自定义函数 tagAttribute 
//功能:获取li标签中的title值
function tagAttribute(){
var ali = document.getElementsByTagName('li'); 
for(var i = 0; i < ali.length; i++){
  if(ali[i].childNodes[0].nodeType == 3){
    alert(ali[i].childNodes[0].nodeValue);
  }
}
}
addOnLoadEvent(tagAttribute); // 为tagAttribute函数绑定到window.onload事件
</script>
</head>
<body>
<h1 id="筱雨生">筱雨生</h1>
<p>時光飛逝,莫讓網絡蹉跎了歲月</p>
<div id="myBlog">
<ul>
<li title="JavaScript">JavaScript</li>
<li title="HTML">HTML</li>
<li title="CSS">CSS</li>
<li title="我的随笔">我的随笔</li>
<li></li>
</ul>
</div>
</body>
</html>

javascript学习笔记 Dom知识点总结

JavaScript的window对象对应着浏览器窗口本身,因此这个对象的属性和方法统称为BOM(浏览器对象模型),如window.open(),window.location等。

JavaScript的document对象是指文档对象模型,主要是处理网页内容。DOM(Document Object Model)即文档对象模型,是针对 HTML 和 XML 文档的 API 。字母D指document(文档),字母O指object(对象),字母指Model(模型)。DOM 描绘了一个层次化的节点树。节点表示一个连接点,文档是由节点构成的集合,DOM的节点主要分为三类:元素节点、文本节点(不是文本内容)、属性节点。

获取节点的名称和类型

1.nodeName属性用来获取节点的名称,文本节点返回#text,元素节点返回标签名称(此时等价于tagName)。语法:目标节点.nodeName
2.nodeType属性用来获取节点的类型,元素节点:1,属性节点:2,文本节点:3。语法:目标节点.nodeType
3.nodeValue属性用来获取和设置节点的值。元素节点返回 null 。语法:目标节点.nodeValue

获取元素节点的方式

1.  document.getElementById

通过ID查找,返回唯一元素节点

2.  document.getElementsByName

通过name属性查找,返回元素节点数组

3.  document.getElementsByTagName

通过标签名称查找,返回元素节点数组

以下三种方法属于HTML5 DOM,并非所有浏览器支持(如某些低版本IE就不支持),属于高级方法

4.  document.getElementsByClassName

通过class属性的类名查找,返回元素节点数组

5.  document.querySelector

通过selector条件获取元素节点,只返回符合条件的第一个元素节点

6.  document.querySelectorAll

通过selector条件获取元素节点,返回所有符合条件的元素节点数组,多条件使用逗号分隔,表示要查找的元素必须符合所有逗号分隔的条件,如果一个元素只符合逗号分隔的条件中的一个,则不会被返回

小结: getElementById和querySelector只返回一个元素节点,而getElementsByName、getElementsByTagName、getElementsByClassName、querySelectorAll返回的是元素节点数组

节点指针

1.childNodes属性用来获取元素节点的子节点,返回节点数组。语法:父节点.childNodes;

2.children属性可以用来获取忽略了空白节点的有效节点(在某些浏览器上,空白符或换行符也是一个文本节点)。语法:父节点.children;

3.firstChild属性可以用来获取元素的第一个子节点,等价于 childNodes[0]。语法:父节点.firstChild;

3.lastChild属性可以用来获取元素的最后一个子节点,等价于 childNodes[childNodes.length-1]。语法:父节点.lastChild;

4.previousSibling属性用来获取目标节点的前一个兄弟节点。语法:目标节点.previousSibling;

5.nextSibling属性用来获取目标节点的后一个兄弟节点。语法:目标节点.nextSibling;

6.parentNode属性用来获取已知节点的父节点。语法:子节点.parentNode;

7.ownerDocument属性用来当前节点所在文档的根节点,等价于document。语法:目标节点.ownerDocument;

节点的操作

1.createElement方法用来创建元素节点。语法:document.createElement('元素标签名称');

2.createAttribute方法用来创建属性节点。语法:document.createAttribute('属性名称');

3.createTextNode方法用来创建文本节点。语法:document.createTextNode('文本内容');

4.appendChild方法用来在目标节点的子节点的末尾添加一个子节点(可以是createElement创建的元素节点,也可以是createTextNode创建的文本节点)。语法:parent.appendChild(要插入的节点);

5.insertBefore方法用来在目标元素的前面插入一个新元素节点,此时的指针在目标元素的父级上。语法:parent.insertBefore(newElement,targetElement);

6.DOM中没有insertAfter这个方法,但是可以通过以下方法来模拟insertAfter;

/*
 * newElement : 要插入的新元素
 * targetElement : 目标元素 
 */
function insertAfter(newElement,targetElement){
 var parent = targetElement.parentNode;
 if(parent.lastChild == targetElement){
 /*
  如果目标元素是parent的最后一个子元素,则把新元素追加到parent元素上,
  也就是在parent的子元素的末尾位置添加新元素 
 */
 parent.appendChild(newElement);
 }else{
 /*
  否则,就把新元素添加到目标元素和目标元素的下一个兄弟元素之间 
 */
 parent.insertBefore(newElement,targetElement.nextSibling);
 }
}

7.replaceChild方法用来替换一个元素节点,此时的指针在目标元素的父级上。语法:parent.replaceChild(replaceElement,targetElement);

8.cloneChild方法用来克隆一个元素节点,传递一个布尔参数,参数为true时表示复制当前节点及其所有子节点,参数为false时表示支付至当前节点。语法:目标元素.cloneChild(true|false);

9.removeChild方法用来删除一个指定节点。语法:removeChild(要删除的节点);

10.getAttribute方法用来获取一个属性的值。语法:目标元素.getAttribute(元素属性名称);

11.setAttribute方法用来设置一个属性的值,没有该属性则创建。语法:目标元素.setAttribute(元素属性名称,属性值);

12.removeAttribute方法用来删除一个属性节点。语法:目标元素.removeAttribute(要删除的属性名称);

DOM操作内容

1.innerHTML属性用来获取和设置HTML内容。语法:元素节点.innerHTML 或者 元素节点.innerHTML = 'HTML字符串';

2.innerText|textContent属性用来获取和设置文本内容。fireFox使用textContent来获取和设置(注意兼容性)。语法:元素节点.innerText 或者 元素节点.innerText = 'HTML字符串';

DOM操作样式

1.style属性用来获取和设置元素的行内样式。语法:element.style;style属性只能获取和设置行内样式,对于如font-size这种样式属性,应该去掉 - 并且将 - 后面的第一个字母大写,驼峰法来获取和设置 如:element.style.fontSize , element.style.backgroundColor

2.getComputedStyle全局方法用来获取计算后的样式,第一个参数是元素节点,第二个参数是类型,如:hover,:active等伪类,默认情况下传 null ,某些IE版本使用currentStyle属性来获取 box.currentStyle。语法:window.getComputedStyle(元素,类型)

3.className属性用来获取和设置元素的样式名称。语法:element.className

4.自定义的 addClass() | hasClass() | removeClass() 方法

//元素是否含有某样式
function hasClass(element,className){
 return !!element.className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'));
}
//向元素添加新样式
function addClass(element,className){
 if(hasClass(element,className) == false){
  element.className += ' '+className;
  }
 }
//移除元素的指定样式
function removeClass(element,className){
 var currentClass = element.className;
 if(hasClass(element,className)){
   currentClass = currentClass.replace(new RegExp('(\\s|^)'+className+'(\\s|$)'),' ');
      //去除空格
   currentClass = currentClass.replace(/(^\s*)|(\s*$)/g,'');
   element.className = currentClass;
 }
}

DOM操作位置和大小

1.clientWidth属性用来获取元素的实际宽度,该值受滚动条和内边距影响,外边距和border不会影响。语法:

element.clientWidth;

2.clientHeight属性用来获取元素的实际高度,该值受滚动条和内边距影响,外边距和border不会影响。语法:

element.clientHeight;

3.offsetWidth属性用来获取元素的实际宽度,该值受边框和内边距影响,外边距和滚动条不会影响。语法:

element.offsetWidth;

4.offsetHeight属性用来获取元素的实际高度,该值受边框和内边距影响,外边距和滚动条不会影响。语法:

element.offsetHeight;

5.offsetTop和offsetLeft属性用来获取元素相对于父级的位置。该值受外边距影响。语法:element.offsetTop ||

element.offsetLeft;

6.scrollTop和scrollLeft属性用来获取滚动条被隐藏的区域大小,也可设置定位到该区域(比如返回顶部)。语法:

element.scrollTop || element.scrollLeft || element.scrollTop = 0;

常用到的简洁快速的document属性和方法

document.title 用来获取文档标题

document.domain 用来获取当前域名

document.URL 用来获取当前url路径

document.forms 获取表单集合

document.images 获取图片集合

document.body 获取body元素节点

document.compatMode 识别文档模式

Statement
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
Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft