search
HomeWeb Front-endJS TutorialCommon methods of Document objects_Basic knowledge

1. getElementById(id)
Access elements through the ID of the element. This is a basic method of accessing page elements in DOM. We need to use it frequently.
For example, in the following example, we You can quickly access it with the ID of the DIV without having to traverse through the DOM layers.
Copy the code The code is as follows:


h


Just for testing;


Just for testing;

<script> <BR>var div=document.getElementById('divid'); <BR>alert(div.nodeName); <BR></script>


Note that when using this function, if the ID of the element is not unique, then the first A qualifying element.
In IE6, if the input, checkbox, radio. and other element names match the specified ID, they will also be accessed
. For example, in the following example, the obtained element is input:
Copy code The code is as follows:




Just for testing;

<script> <BR>var div=document.getElementById('divid' ); <BR>alert(div.nodeName); <BR></script>


2. getElementsByName(name)
Returns an array of elements whose name is name. In IE6, if the element ID matches this name, this element will also be included, and getElementsByName() is only used for element objects such as input, radio, checkbox, etc.
Like the example below, the length of the georges array should be 0.
Copy code The code is as follows:


f

f




3. getElementsByTagName( tagname)
getElementByTagName can be used for DOCUMENT or elements. getElementsByTagName returns a list (array) of child elements with the specified tagname. You can iterate over this array to obtain each individual child element. When dealing with very large DOM structures, this approach makes it easy to narrow down the entire structure.
Copy code The code is as follows:




<script> <BR>function start() { <BR>// Get all elements whose tagName is body (of course only one per page) <BR>myDocumentElements =document.getElementsByTagName("body"); <BR>myBody=myDocumentElements.item(0); <BR>// Get all P elements of body sub-elements <BR>myBodyElements=myBody.getElementsByTagName("p"); <BR>//Get the second P element<BR>myP=myBodyElements.item(1); <BR>//Display the text of this element<BR>alert(myP.firstChild.nodeValue); <BR>} <BR></script>


hi


hello< ;/p>



DOM Element common methods
1. appendChild(node)
Append nodes to the current node object. Often used to dynamically add content to pages.
For example, add a text node to the div as follows:
Copy the code The code is as follows:




In the above example, adding text to DIV can also be achieved using newdiv.innerHTML="A new div".
However, innerHTML does not belong to the DOM.
2. removeChild(childreference)
Remove the current node. The child node of , returns the removed node. The removed node can be inserted elsewhere in the document tree
Copy code The code is as follows:

A child



3 , cloneNode(deepBoolean)
Copy and return the copied node of the current node. The copied node is an isolated node and is not in the document tree. Copies the attribute values ​​of the original node, including the ID attribute, so before adding this new node to the document, be sure to modify the ID attribute to make it unique. Of course, if the uniqueness of the ID is not important, it does not need to be processed.
This method supports a Boolean parameter. When deepBoolean is set to true, all child nodes of the current node will be copied, including the text within the node.
Copy code The code is as follows:

11111
p=document.getElementById("mypara")
pclone = p.cloneNode(true);
p.parentNode.appendChild(pclone);


4 , replaceChild(newChild, oldChild)
Replace a child node of the current node with another node
For example:
Copy code The code is as follows:

span


var oldel=document.getElementById("innerspan");
var newel=document.createElement("p");
var text=document.createTextNode( "ppppp");
newel.appendChild(text);
document.getElementById("adiv").replaceChild(newel, oldel);


5. insertBefore(newElement, targetElement)
Insert a new node into the current node. If targetElement is set to null, the new node is inserted as the last child node. Otherwise, the new node should be inserted as the nearest child node before targetElement. Location.
Copy code The code is as follows:


I want whatever I want!


6. click()
executes a click on the element, which can be used to trigger the onClick function through a script
Copy code The code is as follows:

<script> <BR>function wow() { <BR>alert("I don’t seem to have clicked the mouse." ); <BR>} <BR></script>
hhh



DOM Element attributes: (The following are commonly used. IE5.0 and above are supported by mozllia)
1. childeNodes returns all child node objects,
For example,
Copy code The code is as follows:





A monk has water to drink.
Two monks carry water to drink.
The three monks had no water to drink.

<script> <BR>var msg=”” <BR>var mylist=document.getElementById("mylist") <BR> for (i=0; i<mylist.childNodes.length; i ){ <BR>var tr=mylist.childNodes[i]; <BR>for(j=0;j<tr.childNodes[j].length; j ) { <BR>var td=tr.childNodes[j]; <BR>msg =td.innerText; <BR>} <BR>} <BR>alert(msg); <BR></script>

2. innerHTML
This is a de facto standard and does not belong to w3c DOM, but almost all browsers that support DOM support this attribute. Through this attribute we can easily modify the HTML of an element.
Copy code The code is as follows:

New human, what? ? !




3. style
Return a A reference to the element's style object, through which we can obtain and modify each individual style.
For example, the following script can modify the background color of an element
document.getElementById("test").style.backgroundColor="yellow"
4. firstChild returns the first child node
5. lastChild returns the last child node
6. parentNode returns the object of the parent node.
7. nextSibling returns the object of the next sibling node
8. previousSibling returns the object of the previous sibling node
9. nodeName returns the HTML tag name of the node, using English capital letters, such as P, FONT
For example
Copy code The code is as follows:


<script> <BR>if (document.getElementById("test").nodeName=="DIV") <BR>alert("This is a DIV"); <BR> </script>

First example:
Use DOM1.0 javascript to dynamically create an HTML table.
Copy code The code is as follows:


Sample code
<script> <BR>function start() { <BR>//Get the reference of body<BR>var mybody=document.getElementsByTagName("body").item(0); <BR>//Create a <table> element<BR>mytable = document.createElement("TABLE"); <BR>//Create a <TBODY> element<BR>mytablebody = document.createElement("TBODY"); <BR>//Create rows and columns<BR>for(j=0;j<3;j ) { <BR>//Create a<TR>&gt ;Element<BR>mycurrent_row=document.createElement("TR"); <BR>for(i=0;i<3;i ) { <BR>//Create a <TD> element<BR>mycurrent_cell=document.createElement("TD"); <BR>//Create a text element<BR>currenttext=document.createTextNode("cell is row " j ", column " i); <BR>//Put New text elements are added to the cell TD <BR>mycurrent_cell.appendChild(currenttext); <BR>// appends the cell TD into the row TR <BR>//Add the cell TD into the row TR <BR>mycurrent_row. appendChild(mycurrent_cell); <BR>} <BR>//Add row TR to TBODY <BR>mytablebody.appendChild(mycurrent_row); <BR>} <BR>//Add TBODY to TABLE <BR>mytable. appendChild(mytablebody); <BR>// Add TABLE to BODY <BR>mybody.appendChild(mytable); <BR>// Set the border attribute of mytable to 2 <BR>mytable.setAttribute("border"," 2"); <BR>} <BR></script>



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
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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool