search
HomeWeb Front-endFront-end Q&AHow to get dom elements in javascript

How to get dom elements in javascript

Sep 02, 2021 pm 05:32 PM
javascript

Getting method: 1. "document.getElementById(value)" is obtained through the ID value; 2. "document.getElementsByName(value)" is obtained through the name attribute; 3. "Parent node object.firstChild" is obtained through Get the parent node and so on.

How to get dom elements in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Summary of JavaScript methods for obtaining HTML DOM node elements

In the development of Web applications, especially Web2.0 programs, it is often necessary to obtain An element in the page, and then update the element's style, content, etc. How to obtain the elements to be updated is the first problem to be solved. Fortunately, there are many ways to obtain nodes using JavaScript. Here is a brief summary (the following method was tested in IE7 and Firefox2.0.0.11):

1. Through the top-level document Node acquisition

(1) document.getElementById(elementId): This method can accurately obtain the required element through the ID of the node, which is a relatively simple and fast method. If the page contains multiple nodes with the same ID, only the first node will be returned.

Nowadays, many JavaScript libraries such as prototype and Mootools have appeared, which provide a simpler method: $(id), and the parameter is still the id of the node. This method can be regarded as another way of writing document.getElementById(), but the function of $() is more powerful. For specific usage, please refer to their respective API documents.

(2)document.getElementsByName(elementName): This method obtains the node through the name of the node. As can be seen from the name, this method does not return a node element, but a node element. An array of nodes with the same name. Then, we can loop through a certain attribute of the node to determine whether it is the required node.

For example: In HTML, checkbox and radio use the same name attribute value to identify elements in a group. If we want to get the selected element now, we first get the shuffled element, and then loop to determine whether the checked attribute value of the node is true.

(3)document.getElementsByTagName(tagName): This method obtains the node through its Tag. This method also returns an array, for example: document.getElementsByTagName('A') All hyperlink nodes on the page will be returned. Before obtaining the node, the type of the node is generally known, so it is relatively simple to use this method. But the disadvantage is also obvious, that is, the returned array may be very large, which will waste a lot of time. So, is this method useless? Of course not. This method is different from the two above. It is not a proprietary method of the document node and can also be applied to other nodes, which will be mentioned below.

2. Get

through the parent node (1) parentObj.firstChild: If the node is the first of the known nodes (parentObj) This method can be used for child nodes. This attribute can be used recursively, that is, it supports the form of parentObj.firstChild.firstChild.firstChild..., so that deeper nodes can be obtained.

(2)parentObj.lastChild: Obviously, this attribute is to get the last child node of the known node (parentObj). Like firstChild, it can also be used recursively.
In use, if we combine the two, we will achieve a more exciting effect, namely: parentObj.firstChild.lastChild.lastChild...

(3) parentObj.childNodes: Get the child node array of a known node, and then find the required node through looping or indexing.

Note: After testing, it was found that on IE7, what is obtained is the array of direct child nodes, while on Firefox2.0.0.11, what is obtained is all child nodes, including the child nodes of the child node.

(4)parentObj.children: Get the direct child node array of a known node.

Note: After testing, on IE7, the effect is the same as childNodes, but Firefox2.0.0.11 does not support it. This is why I use a different style than other methods. Therefore its use is not recommended.

(5)parentObj.getElementsByTagName(tagName): The usage method will not be described in detail. It returns an array of child nodes of the specified value among all child nodes of the known node. For example: parentObj.getElementsByTagName('A') returns all hyperlinks in known child nodes.

3. Get

through adjacent nodes (1) neighbourNode.previousSibling: Get the previous node of the known node (neighbourNode), this Like the previous firstChild and lastChild properties, it seems that they can be used recursively.

(2)neighbourNode.nextSibling: Get the next node of the known node (neighbourNode), also supports recursion.

4. Get

through child nodes (1) childNode.parentNode: Get the parent node of a known node.

The methods mentioned above are just some basic methods. If you use JavaScript libraries such as Prototype, you may also get other different methods, such as obtaining through the class of the node, etc. However, if you can flexibly use the above methods, I believe you should be able to handle most programs.

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to get dom elements in 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
How to change the background color of a navbar in BootstrapHow to change the background color of a navbar in BootstrapAug 26, 2025 am 05:19 AM

UseBootstrap’sbuilt-inbackgroundcolorclasseslikebg-primary,bg-success,orbg-darkandpairwithnavbar-darkornavbar-lightforpropertextcontrast.2.Applycustomcolorsbyaddingacustomclasstothenavbaranddefiningthebackground-colorinCSSusinghex,RGB,orRGBAvaluesfor

What are physical and logical tags in HTML?What are physical and logical tags in HTML?Aug 26, 2025 am 05:10 AM

Physical tags are used to define the appearance of text, and logical tags are used to define the meaning of text; 1. Physical tags such as , directly control styles, but modern development recommends using CSS instead; 2. Logical tags such as , give content semantics, improve accessibility and SEO, and should be used first; 3. Modern HTML advocates the separation of structure and styles, emphasizing the combination of semantic tags and CSS to achieve a more maintainable, responsive and barrier-free web page.

How to use the meter tag in HTMLHow to use the meter tag in HTMLAug 26, 2025 am 03:44 AM

Thetagisusedtodisplayascalarmeasurementwithinaknownrange,suchasaquizscoreordiskusage,andrendersasahorizontalgauge;2.Keyattributesincludevalue(required),min,max,low,high,optimum,andtitleforaccessibility;3.Visualrangesaredefinedbylow,high,andoptimumtoi

How to animate a button with CSSHow to animate a button with CSSAug 26, 2025 am 02:17 AM

UseCSStransitionsforsmoothhovereffectsbyapplyingtransitionpropertiestobackground-color,transform,andbox-shadowtocreatesubtleanimations.2.Addscaleorcolortransformationswithtransform:scale()andcolorchangestoenhanceinteractivitywhilekeepingchangesminima

How to use article and section tags in HTMLHow to use article and section tags in HTMLAug 26, 2025 am 01:23 AM

Use tags for independent, self-containable content, such as blog posts, news stories, product lists or user comments, which can exist independently even if they are out of context; use tags for grouping related content with the same topic, usually containing a title, such as the "Services" or "Latest Articles" block in the page; 1. Emphasize the independence of the content, which can be aggregated or shared; 2. Emphasize the logical grouping of the content, which should have clear themes and titles; 3. Both can be used in nested, such as one containing multiples, or one divided into multiples; 4. Avoid using only for style, without topics or titles; 5. Correct use of these semantic tags can improve accessibility, SEO and code readability, making the web page structure clearer and easier to understand.

How to create a responsive services section with CSSHow to create a responsive services section with CSSAug 26, 2025 am 01:10 AM

StartwithsemanticHTMLusingasectioncontainerandservicecardsforclarity.2.UseCSSFlexboxorGridtocreateaflexiblelayout,withFlexboxforsimplerlayoutsandGridformorecontrol.3.Applyresponsivedesignviamediaqueries:stackcardsonsmallscreens,displaytwoperrowontabl

How to use conditional comments in HTMLHow to use conditional comments in HTMLAug 25, 2025 pm 01:43 PM

ConditionalcommentsweresupportedonlyinInternetExplorer5through9andarenotavailableinmodernbrowsersorstandards.1.TheyalloweddeveloperstotargetspecificIEversionsusingspecialHTML-likesyntaxrecognizedonlybyIE.2.Commonconditionsincluded"IE","

How to use the source element in HTMLHow to use the source element in HTMLAug 25, 2025 pm 12:03 PM

Using elements can provide multiple media formats in or in tags. The browser selects the first supported format in order and uses type attributes to avoid downloading unsupported files; 2. Using elements in the elements can load different images according to the screen size or resolution, match the conditions through the media attribute and serve as the final fallback; 3. Always add type attributes, sort source files by priority, optimize performance in responsive design, and tests across browsers to ensure compatibility, do not render content itself, and only provide optional resources for the parent element.

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

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.

Hot Topics