search
HomeWeb Front-endJS Tutorial8 ways to get HTML DOM elements using javascript

8 ways to get HTML DOM elements using javascript

Jun 28, 2017 am 11:41 AM
htmljavascriptjs

This article mainly introduces the 8 methods of obtaining HTML DOM elements with JS in detail. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

What is HTML DOM

Document Object Model (Document Object Model) is recommended by the W3C organization Standard programming interface for handling extensible markup languages. A simple understanding is that HTML DOM is a standard on how to obtain, modify, add or delete HTML elements. All operations we perform on web pages using JavaScript are performed through the DOM.

This article does not do in-depth research, but only summarizes various usages and pitfalls.

JS methods to get DOM elements (8 ways)

  1. Get by ID (getElementById)

  2. By name attribute (getElementsByName)

  3. By tag name (getElementsByTagName)

  4. By class name (getElementsByClassName)

  5. Method to get html (document.documentElement)

  6. Method to get body (document.body)

  7. Get an element through the selector (querySelector)

  8. Get a group of elements through the selector (querySelectorAll)

Let’s start explaining one by one.

1. Get by ID (getElementById)

document.getElementById('id')

Usage:

1. The context must be document.

2. Parameters must be passed. The parameters are of string type and are used to obtain the id of the element.

3. The return value only obtains one element, and returns null if it is not found.

pit~~pit pit~pit pit~pit pit~:

1. If there are multiple ids, only the first one is obtained, that is, which one appears first . Generally, the same ID will not appear twice on the page.

2. In IE6 and 7, the name of the form element will be obtained as the ID value. So everyone must pay attention when defining these.

3. It is not case sensitive in IE6 and 7.

4. You can directly use the ID of the element to represent this element. (Not recommended in the project)

5. The context of the element obtained through ID can only be document. Why does the context have to be document? Because the getElementById method is on the prototype of the Document class. Maybe you don’t understand, so continue reading.

2. Through the name attribute (getElementsByName)

document.getElementsByName('name')

Usage:

1. The context must be document.

2. Parameters must be passed, and the parameters are to obtain the name attribute of the element.

3. The return value is an array-like array. If not found, an empty array is returned.

pit~~pit pit~pit pit~pit pit~:

1. The obtained result is an array-like, not an array.

2. Only form elements can be obtained in IE browser. Of course, we generally only use it to obtain form elements. Starting from ie10, it can be more than just form elements.

3. The context can only be document, for the same reason as getElementById.

3. By tag name (getElementsByTagName)

document.getElementsByTagName('p');
var op = document.getElementById('pId');
op.getElementsByTagName('p');

Usage:

1. The context can be document or It is an element. Note that this element must exist.

2. The parameter is to obtain the tag name attribute of the element, which is not case-sensitive.

3. The return value is an array-like array. If not found, an empty array is returned.

pit~~pit pit~pit pit~pit pit~:

1. The obtained result is an array-like.

2. The context does not have to be a document, because the getElementsByTagName method is not only on the prototype of the Document class but also on the prototype of the Element class, so both document and element can be Use this method. If you still don’t understand, I will explain it at the end of the article.

4. Through the class name (getElementsByClassName)

Usage (similar to getElementsByTagName):

1. The context can be document, can also be an element.

2. The parameter is the class name of the element.

3. The return value is an array-like array. If not found, an empty array is returned.

pit~~pit pit~pit pit~pit pit~:

1. The obtained result is an array-like.

2.IE8 and previous versions are not compatible. It's a pity that such a useful method is not compatible.

5. Method to obtain html (document.documentElement)

document.documentElement is specially used to obtain the html tag.

6. Method to obtain body (document.body)

document.body is specially used to obtain the body tag.

7. Get an element through the selector (querySelector)

Usage:

1. The context can be document, Can also be an element.

2. The parameter is a selector, such as: "p .className".

3. The return value only obtains one element.

pit~~pit pit~pit pit~pit pit~:

This method is not compatible with IE7 and previous versions, and it seems that companies that are compatible with IE7 are not considered now.

8. Get a set of elements through the selector (querySelectorAll)

Usage is similar to querySelector:

1. Context It can be a document or an element.

2. The parameter is a selector, such as: "p .className".

3. The return value is an array-like.

pit~~pit pit~pit pit~pit pit~:

Same as querySelector, not compatible with IE7.

Now that we have finished talking about the 8 methods of obtaining DOM elements using native JS, let’s talk about why some methods can only be used on documents.

Take p as an example. p is an instance of the HTMLpElement class, and document is an instance of HTMLDocument.

Their inheritance relationship:

HTMLpElement > HTMLElement > Element > Node > EventTarget

HTMLDocument > Document > Node > ; EventTarget

We all know that subclasses inherit the parent class, and the subclass can use the properties and methods of the parent class.

Their same inheritance relationship is Node and EventTarget, which means they can all use the methods on Node and EventTarget.

Such as nodeName, parentNode, etc. on Node, and addEventListener on EventTarget, etc.

getElementById is only on the prototype of the Document class. HTMLpElement does not inherit the Document class, so p cannot use the getElementById method.
getElementsByTagName is on the prototype of the Document class and also on the prototype of the Element class, so both p and document can use the getElementsByTagName method.

Others are the same.

The above is the entire content of this article. I hope it will be helpful to everyone's study. I also hope that everyone will support Script House.

The above is the detailed content of 8 ways to get HTML DOM elements using javascript. 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
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.

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.

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools