search
HomeWeb Front-endJS TutorialJavaScript complete summary of DOM Elements

JavaScript complete summary of DOM Elements

May 21, 2018 pm 02:00 PM
domelementjavascript

We often encounter some problems with javascript dom in our studies, so this article will explain them.

In addition to the document object, the most commonly used element object in DOM is the Element object, which represents HTML elements.

Element objects can have child nodes of type element nodes, text nodes, and comment nodes. DOM provides a series of methods to add, delete, modify, and query elements

Element There are several important attributes

nodeName: element tag name, and a similar tagName
nodeType: element type
className: class name id: element idchildren: child element list (HTMLCollection)
childNodes: child element list (NodeList)
firstChild: the first child element
lastChild: the last child element
nextSibling: the next sibling element
previousSibling: the previous sibling element
parentNode , parentElement: parent element

Query element

getElementById
method returns the element node that matches the specified ID attribute. If no matching node is found, null is returned. This is also the fastest way to get an element.

var elem = document.getElementById("test");getElementsByClassName()
getElementsByClassName

The method returns an array-like object (HTMLCollection type object), including all elements whose class names meet the specified conditions (the search range includes itself), and changes in the elements. Reflected in the returned results in real time. This method can be called not only on the document object, but also on any element node.

var elements = document.getElementsByClassName(names);//getElementsByClassName方法的参数,可以是多个空格分隔的class名字,返回同时具有这些节点的元素。
document.getElementsByClassName('red test');```
* getElementsByTagName()

getElementsByTagName method returns all elements with the specified tag (the search scope includes itself). The return value is an HTMLCollection object, that is to say, the search results are a dynamic collection, and changes in any elements will be reflected in the returned collection in real time. This method can be called not only on the document object, but also on any element node.

var paras = document.getElementsByTagName("p");
//上面代码返回当前文档的所有p元素节点。注意,getElementsByTagName方法会将参数转为小写后,再进行搜索。```
getElementsByName()
getElementsByName方法用于选择拥有name属性的HTML元素,比如form、img、frame、embed和object,返回一个NodeList格式的对象,不会实时反映元素的变化。

// Assume there is a form

var forms = document.getElementsByName("x");
forms[0 ].tagName // "FORM" // Note that when using this method in IE browser, elements that do not have a name attribute but have an id attribute with the same name will also be returned, so it is best to set the name and id attributes to different values. ```* querySelector()
querySelector method returns element nodes that match the specified CSS selector. If multiple nodes meet the matching criteria, the first matching node is returned. If no matching node is found, null is returned.
var el1 = document.querySelector(".myclass");
var el2 = document.querySelector('#myParent > [ng-click]');
//querySelector方法无法选中CSS伪元素。```
querySelectorAll()
querySelectorAll方法返回匹配指定的CSS选择器的所有节点,返回的是NodeList类型的对象。NodeList对象不是动态集合,所以元素节点的变化无法实时反映在返回结果中。
elementList = document.querySelectorAll(selectors);//querySelectorAll方法的参数,可以是逗号分隔的多个CSS选择器,返回所有匹配其中一个选择器的元素。var matches = document.querySelectorAll("div.note, div.alert");//上面代码返回class属性是note或alert的div元素。
elementFromPoint()
elementFromPoint方法返回位于页面指定位置的元素。
var element = document.elementFromPoint(x, y);//上面代码中,elementFromPoint方法的参数x和y,分别是相对于当前窗口左上角的横坐标和纵坐标,单位是CSS像素。
elementFromPoint方法返回位于这个位置的DOM元素,如果该元素不可返回(比如文本框的滚动条),则返回它的父元素(比如文本框)。如果坐标值无意义(比如负值),则返回null。

Creating elements

createElement()
createElement方法用来生成HTML元素节点。
var newDiv = document.createElement("div");//createElement方法的参数为元素的标签名,即元素节点的tagName属性。//如果传入大写的标签名,会被转为小写。如果参数带有尖括号(即<和>)或者是null,会报错。
createTextNode()
createTextNode方法用来生成文本节点,参数为所要生成的文本节点的内容。
var newDiv = document.createElement("div");var newContent = document.createTextNode("Hello");//上面代码新建一个div节点和一个文本节点
createDocumentFragment()
//createDocumentFragment方法生成一个DocumentFragment对象。var docFragment = document.createDocumentFragment();```

The DocumentFragment object is a DOM fragment that exists in memory, but does not belong to the current document. It is often used to generate more complex DOM structures and then insert them into the current document. . The advantage of this is that because the DocumentFragment does not belong to the current document, any changes to it will not cause the web page to be re-rendered, which has better performance than directly modifying the DOM of the current document.

##Modify elements

* appendChild()
Add an element to the end of an element

var newDiv = document.createElement("div");var newContent = document.createTextNode("Hello");newDiv.appendChild(newContent);```
insertBefore()

Insert an element before an element

var newDiv = document.createElement("div");var newContent = document.createTextNode("Hello");newDiv.insertBefore(newContent, newDiv.firstChild);replaceChild()
replaceChild()

Accepts two parameters: the element to be inserted and the element to be replaced

newDiv.replaceChild(newElement, oldElement);```
* removeChild()

Delete element

parentNode.removeChild(childNode);```
cloneNode()

Clone element, the method has a boolean parameter , when true is passed in, it will be deeply copied, that is, the element and its sub-elements will be copied (IE will also copy its events), when false, only the element itself will be copied

node.cloneNode(true);```##属性操作* getAttribute()
//getAttribute()用于获取元素的attribute值node.getAttribute(&#39;id&#39;);```
createAttribute()
//createAttribute()方法生成一个新的属性对象节点,并返回它。attribute = document.createAttribute(name);
createAttribute方法的参数name,是属性的名称。

setAttribute()

//setAttribute()方法用于设置元素属性var node = document.getElementById("div1");
node.setAttribute("my_attrib", "newVal");//等同于var node = document.getElementById("div1");var a = document.createAttribute("my_attrib");
a.value = "newVal";
node.setAttributeNode(a);```
* romoveAttribute()
removeAttribute()用于删除元素属性
node.removeAttribute(&#39;id&#39;);
element.attributes

Of course, what the above method does can also be achieved by class operation array attribute element.attributes


#HTMLCollection and NodeList We know that the Element object represents an element, so a collection of multiple elements There are generally two data types. The NodeList object represents an ordered node list. HTMLCollection is an interface that represents a collection of HTML elements. It provides methods and attributes that can traverse the list.

The following method obtains the HTMLCollection object

document.images //所有img元素
document.links //所有带href属性的a元素和area元素
document.anchors //所有带name属性的a元素
document.forms //所有form元素
document.scripts //所有script元素
document.applets //所有applet元素
document.embeds //所有embed元素
document.plugins //document.与embeds相同
document.getElementById("table").children
document.getElementById("table").tBodies
document.getElementById("table").rows
document.getElementById("row").cells
document.getElementById("Map").areas
document.getElementById("f2").elements //HTMLFormControlsCollection extends HTMLCollection
document.getElementById("s").options //HTMLOptionsCollection extends HTMLCollection```

The following methods obtain NodeList objects

document.getElementsByName("name1")
document.getElementsByClassName("class1")
document.getElementsByTagName("a")
document.querySelectorAll("a")
document.getElementById("table").childNodes
document.styleSheets //StyleSheetList,与NodeList类似```#####HTMLCollection与NodeList有很大部分相似性* 都是类数组对象,都有length属性,可以通过for循环迭代

* are all read-only

* are real-time, that is, changes to the document will be immediately Reflected on the relevant objects (with one exception, the NodeList returned by document.querySelectorAll is not real-time)

* All have item() methods, and elements can be obtained through item(index) or item("id")
##The difference is that * HTMLCollection object has namedItem() method, you can pass id or name to obtain elements

* HTMLCollection's item() method and obtaining elements through attributes (document.forms.f1) can support id and name, while the NodeList object only supports id

###This article provides a relevant explanation of dom. For more related content, please pay attention to the php Chinese website. ###

The above is the detailed content of JavaScript complete summary of DOM Elements. For more information, please follow other related articles on the PHP Chinese website!

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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool