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

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools