This article mainly introduces the detailed explanation of javascript DOM and relevant information about example codes. Friends in need can refer to
javascript DOM Summary
I have always thought that DOM (DocumentObjectModel) is the simplest part of JS. It is undeniable that it is indeed very simple, because the thinking mode of DOM is a bit fixed, and you only need to simply remember some fixed methods, so DOM can be said to be the starting point for all js (here refers to client js).
Recently, when I was doing some useful DOM exercises, I found that my DOM knowledge was very fragmented (I always thought I had a good grasp of it). Many friends may think that DOM is just a matter of calling Call a few methods, or I use jQuery directly, without having to consider the details of the DOM at all. Yes, that’s right. jQuery’s encapsulation of DOM is unprecedented, but just like growing up, you must be able to walk before you can run, so I think you must have a more detailed understanding of DOM, so I summarized the following about DOM Some usage methods.
In the W3C summary of DOM specifications, there are some that are very commonly used and some that are not very useful. Here we mainly discuss some commonly used DOM operations (related to DOM The basic concepts of will not be introduced here):
Node level
The so-called node level refers to the html document# There are nodes (such as tags) with their own characteristics, data, and methods in ##, and the relationship between nodes constitutes a hierarchy (in fact, it can be imagined as a tree structure). A NODE interface is defined in the W3C's DOM level 1 specification. This interface has some methods that are very useful:
Node.ELEMENT_NODE;(Element node)
Node.TEXT_NODE;(Text node)
Node.DOCUMENT_NODE (document node)
Each node has its own node type flag, which is the NodeType attribute, for example, the nodeType of the element node == ' 1';The nodeType of the text node == '3';The nodeType of the document node == '9';1. Document node
The document node is in a document It is represented by the document object, and its basic characteristics are as follows:console.log(document.nodeType); // 9 console.log(document.nodeName); // #document console.log(document.nodeValue); // null console.log(document.parentNode); // null(它已经是最顶层的节点,树的根节点)Tip one (child node of the document): 1.Document.documentElement can get the html object, and it can also be obtained through document. Get childNodes[0] and document.firstchild. However, documentElement provides faster, more direct access to elements. tip two (document related information): 1. Get the document title: document.title; 2. Get the complete url: document.URL; 3. Get the domain name (ip): document.domain; 4. Get the URL of the page: document.referrer; tip three (document search element):
1. By id: document.getElementById("xxx"); Generally, the page ids will be different. If there are multiple identical ids, the first element with that id will be fetched. 2. Through tagName: document.getElementsByTagName("xxx"); Return the collection of elements with the tag name "xxx"! 3. Through name: document.getElementByName(); It is very simple to understand the document object, and the compatibility is also relatively advanced.
2. Element node
The element node provides access to the element tag name, sub-nodes and attributes. Its basic characteristics are as follows:var ele = document.getElementById("element"); //通过document取到一个标签对象 console.log(ele.nodeType); // 1 console.log(ele.nodeName); // 返回元素的标签名 console.log(ele.nodeValue); //永远返回null!
tip one (html element):
<p id="myp" class="bd" title="Body text" lang="en" dir="ltr"></p> var p = document.getElementById("p"); 1. console.log(p.id); // "myp" 2. console.log(p.className); // "bd" 3. console.log(p.title); // "Body text" 4. console.log(p.lang); // "en" 5. console.log(p.dir); // "ltr"tip two (get, set and delete attributes):
1.p.getAttribute("id"); // "myp" 2.p.setAttribuye("id","yourp"); // id已变动 3.p.removeAttribute("id"); //id已删除It should be noted: In IE7 and below versions, there are some abnormal behaviors in the three methods. Setting the class and style attributes through set, especially when tip three (child node of the element): What I want to focus on is here, the following code:
<ul id="myList"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> var mL = document.getElementById("myList"); //很明显mL对象有三个元素节点,我们也知道用childNodes属性去找到节点数,然而陷阱随之而来 console.log(mL.childNodes); // 7 //?!怎么会有7个? //原因在于childNodes中不仅包含了元素节点,还有4个文本节点。因此需要过滤 for(var i=0,len=ml.childNodes.length;i<len;i++){ if(ml.childNodes[i].nodeType == "1"){ // 利用元素节点的特性 // .... } }<br>//最好的方法可以这么做<br>//如果元素对象内部标签名是一样的<br>var items = ml.getElementsByTagName("li"); //能得到三个li节点对象
3. Text node
Text nodes contain plain text content that can be interpreted literally. Plain text can contain escaped HTML characters, but cannot contain HTML codes. The basic characteristics of text nodes are as follows:<p id="myp">123</p> var myp = document.getElementById("myp") //取到元素节点 var tx = myp.childNodes[0] //前面也提过childNodes的特性,这次取到了文本节点 console.log(tx.nodeType) // 3 console.log(tx.nodeName) // 所有文本节点的nodeName都是"#text"; console.log(tx.nodeValue) // 123(节点包含的文本),注意元素节点是不能取到它包含的文本节点的文本的 //所以其父节点显然是个元素节点.Tip one: Two methods to create text nodes: document.createTextNode(),document.createText(); Create Once completed, it will not be directly embedded in the document and will need to be quoted.
var a = document.createElement("p"); var b = document.createTextNode("123"); a.appendChild(b); document.body.appendChild(a);In this way, a tag like
123
will appear at the end of the bodyPersonally, I think DOM is definitely the entry point for learning js, but it also takes a long time to polish. I have read the DOM no less than three times, it is only the DOM level 1 specification, and there is something new every time. If you learn DOM, you must pay attention to some pitfalls and spend more time thinking about them.
The above is the detailed content of Detailed explanation of sample code of javascript DOM. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools
