search
HomeWeb Front-endJS TutorialN ways to obtain elements in JS and their dynamic and static discussions

In the process of learning JavaScript, you will encounter the problem of js obtaining elements. This article will explain the method of obtaining elements.

In actual front-end development work, we often encounter the need to obtain certain elements in order to update the style, content, etc. of the element. The Document Object Model (DOM) is a programming interface for HTML and XML documents. It provides a structured representation of the document and defines a way to access the structure from the program, thereby changing the structure and style of the document. and content. The DOM parses a document into a structured collection of nodes and objects (objects containing properties and methods), which connects web pages to scripts or programming languages. Therefore, JavaScript can obtain element nodes through the DOM API. The methods are as follows: querySelector() and querySelectorAll() are the ES5 element selection methods

1, getElementById():

Receives a parameter: the ID of the element to be obtained (case-sensitive, must match strictly), returns an Element object (can also be regarded as a dynamic NodeList collection, except that the collection only contains one matching element, but it will also reflect the DOM in real time Node changes), if the element with a specific ID does not exist in the current document, nul is returned.
Syntax:

element = document.getElementById(id);

Example: Delete

<body>
    <div id="myDiv">
        <p class="myP">hello world</p>
        <p class="myP">hello dolby</p>
        <p class="myP">hello dot</p>
        <p class="myP">hello bean</p>
    </div>
    <script>
        var div = document.getElementById("myDiv");        console.log(div); //(1)
        var body=document.querySelector(&#39;body&#39;);
        body.removeChild(div);        console.log(body); //(2)
    </script></body>
//(1)处打印值    <div id="myDiv">
        <p class="myP">hello world</p>
        <p class="myP">hello dolby</p>
        <p class="myP">hello dot</p>
        <p class="myP">hello bean</p>
    </div>//(2)处打印值<body>
    <script>
        var div = document.getElementById("myDiv");        console.log(div); //(1)
        var body=document.querySelector(&#39;body&#39;);
        body.removeChild(div);        console.log(body); //(2)
    </script></body>

Example:

<!DOCTYPE html><html><head>
  <title>getElementById example</title>
  <script>
  function changeColor(newColor) {    var elem = document.getElementById("para1");
    elem.style.color = newColor;
  }  </script></head><body>
  <p id="para1">Some text here</p>
  <button onclick="changeColor(&#39;blue&#39;);">blue</button>
  <button onclick="changeColor(&#39;red&#39;);">red</button></body></html>

getElementById( ) method will not search for elements that are not in the document. After creating an element and assigning an ID, you must use insertBefore() or other similar methods to insert the element into the document before you can use getElementById() to obtain:

var element = document.createElement("div");
element.id = &#39;testqq&#39;;var el = document.getElementById(&#39;testqq&#39;); // el will be null!

2, getElementsByClassName():

Receives a parameter, which is a string containing one or more class names (class names are separated by spaces), and returns an HTMLCollection dynamic collection (it can also be said to return a NodeList class array object), which contains the current element. As the root node, all child elements with specified class names.
Syntax:

var elements = document.getElementsByClassName(names); 
var elements = rootElement.getElementsByClassName(names);

getElementsByClassName can be called on any element, not just document. The element calling this method will be used as the root element for this search.
Example:

Get all elements with class 'test':

document.getElementsByClassName('test');

Get all elements including class Elements of 'red' and 'test':

document.getElementsByClassName('red test');

In the child nodes of the element with the id of 'main', get all Elements with class 'test':

document.getElementById('main').getElementsByClassName('test');

Example: Delete

//html代码<div class="myDiv">
        <p class="myP">hello world</p>
        <p class="myP">hello dolby</p>
        <p class="myP">hello dot</p>
        <p class="myP">hello bean</p>
    </div>
//js代码一    <script>
        var div = document.getElementsByClassName("myDiv");        console.log(div); //(3)
        var p = document.getElementsByClassName("myP");        for (var i = 0; i < p.length; i++) {
            div[0].removeChild(p[i]);
        }        console.log(p); //(4)
    </script>

/ /Print value at (3)
[div.myDiv] //A dynamic HTMLCollection collection, length is 1, innerHTML is

hello dolby

,

hello bean

, why there are no other two p elements will be explained later.

//Print value at (4)
[p.myP,p.myP] //A dynamic HTMLCollection collection with a length of 2 and innerHTML respectively "hello dolby" and "hello bean" .

The above method of deleting nodes has been used to verify that the getElementsByClassName method returns an HTMLCollection dynamic collection.

⬆️In the above code, first div obtains a dynamic collection composed of elements with the class name "myDiv" in the page, p obtains a dynamic collection composed of elements with the class name "myP" in the page, and then uses A for loop to delete each item in the "myP" collection in the first item in the "myDiv" collection (that is, the only div element in the above example). As a result, only the first and third items are deleted. This is why?
The reason is that changes in the DOM structure in the dynamic collection can be automatically reflected in the saved objects. Initially p.legth=4, when i=0, the first p element in the page is deleted, and thereafter p.length= 3; When i=1, the item with index 1 in the remaining three p is deleted, and then p.length=2; when i=2, the condition of i

So how can we traverse each item in the HTMLCollection collection of array-like objects and delete all items?
It’s still a for loop⬇️, just delete the last item in the object collection each time ~

//js代码二    <script>
        var div = document.getElementsByClassName("myDiv")[0];        console.log(div); //(5)
        var p = document.getElementsByClassName("myP");        for (var i=p.length;i--;){
            div.removeChild(p[i]);
        }        console.log(p); //(6)
    </script>
//(5)处打印值<div class="myDiv"></div>//(6)处打印值[] //空的HTMLCollection集合,长度为0

3. getElementsByTagName():

Receives one parameter: to be obtained The tag name of the element (not case sensitive), returns an HTMLCollection dynamic collection (it can also be said to return a NodeList class array object), the collection contains the current element as the root node (excluding the current element itself), all the specified tag names Child elements, the order of child elements is the order in which they appear in the subtree of the current element. If no element is found, the set will be empty.
Syntax:

elements = element.getElementsByTagName(tagName)

Example:

// check the alignment on a number of cells in a table. var table = document.getElementById("forecast-table"); 
var cells = table.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
    var status = cells[i].getAttribute("data-status"); 
    if ( status == "open" ) { 
        // grab the data 
    }
}

Example: Delete

<body>
    <div id="myDiv">
        <p class="myP">hello world</p>
        <p class="myP">hello dolby</p>
        <p class="myP">hello dot</p>
        <p class="myP">hello bean</p>
    </div>
    <script>
        var div = document.getElementById("myDiv");        console.log(div); //(7)
        var p = document.getElementsByTagName("p");//

以下for循环改为for (var i=0,len=p.length;i        for (var i=p.length;i--;){
           div.removeChild(p[i]);
       }        console.log(p); //(8)
   

The above is the detailed content of N ways to obtain elements in JS and their dynamic and static discussions. 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
Java vs JavaScript: A Detailed Comparison for DevelopersJava vs JavaScript: A Detailed Comparison for DevelopersMay 16, 2025 am 12:01 AM

JavaandJavaScriptaredistinctlanguages:Javaisusedforenterpriseandmobileapps,whileJavaScriptisforinteractivewebpages.1)Javaiscompiled,staticallytyped,andrunsonJVM.2)JavaScriptisinterpreted,dynamicallytyped,andrunsinbrowsersorNode.js.3)JavausesOOPwithcl

Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

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.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

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

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

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.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

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: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

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.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

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

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

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.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!