Home Web Front-end JS Tutorial Common methods of Document objects_Basic knowledge

Common methods of Document objects_Basic knowledge

May 16, 2016 pm 06:48 PM
document object

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

< script type="text/javascript">
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!



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></table> element<br>mytable = document.createElement("TABLE"); <br>//Create a <TBODY></TBODY> element<br>mytablebody = document.createElement("TBODY"); <br>//Create rows and columns<br>for(j=0;j<3;j ) { <BR>//Create a<TR></TR&gt ;Element<BR>mycurrent_row=document.createElement("TR"); <BR>for(i=0;i<3;i ) { <BR>//Create a <TD></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>





First, we create a table element
Next, create a TBODY element, which should be a child element of the TABLE element,
But now there is no connection between them.
Next, use a loop to create TR elements, which should be children of the TBODY element.
For each TR, we use a loop to create TD elements, which are children of TR.
For each TD, we create a text node element
Now, we have created these TABLE, TBODY, TR, TD and text elements, but the hierarchical
relationship between them has not been established. . Then we add each object to its parent node in reverse order.
mycurrent_cell.appendChild(currenttext);
mycurrent_row.appendChild(mycurrent_cell);
mytablebody.appendChild(mycurrent_row);
mytable.appendChild(mytablebody);
Now the DOM hierarchy is as follows:
BODY

TABLE

TBODY

TR-------------------TR------- -----------TR

TD-----TD-----TD TD-----TD-----TD TD----- TD-----TD
Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Convert an array or object to a JSON string using PHP's json_encode() function Convert an array or object to a JSON string using PHP's json_encode() function Nov 03, 2023 pm 03:30 PM

JSON (JavaScriptObjectNotation) is a lightweight data exchange format that has become a common format for data exchange between web applications. PHP's json_encode() function can convert an array or object into a JSON string. This article will introduce how to use PHP's json_encode() function, including syntax, parameters, return values, and specific examples. Syntax The syntax of the json_encode() function is as follows: st

Use Python's __contains__() function to define the containment operation of an object Use Python's __contains__() function to define the containment operation of an object Aug 22, 2023 pm 04:23 PM

Use Python's __contains__() function to define the containment operation of an object. Python is a concise and powerful programming language that provides many powerful features to handle various types of data. One of them is to implement the containment operation of objects by defining the __contains__() function. This article will introduce how to use the __contains__() function to define the containment operation of an object, and give some sample code. The __contains__() function is Pytho

How to convert MySQL query result array to object? How to convert MySQL query result array to object? Apr 29, 2024 pm 01:09 PM

Here's how to convert a MySQL query result array into an object: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

Source code exploration: How are objects called in Python? Source code exploration: How are objects called in Python? May 11, 2023 am 11:46 AM

Wedge We know that objects are created in two main ways, one is through Python/CAPI, and the other is by calling a type object. For instance objects of built-in types, both methods are supported. For example, lists can be created through [] or list(). The former is Python/CAPI and the latter is a calling type object. But for instance objects of custom classes, we can only create them by calling type objects. If an object can be called, then the object is callable, otherwise it is not callable. Determining whether an object is callable depends on whether a method is defined in its corresponding type object. like

How to solve the problem that document.cookie cannot be obtained How to solve the problem that document.cookie cannot be obtained Nov 23, 2023 am 10:02 AM

Solutions for document.cookie not being obtained: 1. Browser privacy settings; 2. Same-origin policy; 3. HTTPOnly Cookie; 4. JavaScript code error; 5. Cookie does not exist or expires; 6. Cross-domain issues; 7. Viewer mode; 8. Server problems; 9. JavaScript execution timing; 10. Check console log, etc.

How do PHP functions return objects? How do PHP functions return objects? Apr 10, 2024 pm 03:18 PM

PHP functions can encapsulate data into a custom structure by returning an object using a return statement followed by an object instance. Syntax: functionget_object():object{}. This allows creating objects with custom properties and methods and processing data in the form of objects.

Use Python's __le__() function to define a less than or equal comparison of two objects Use Python's __le__() function to define a less than or equal comparison of two objects Aug 21, 2023 pm 09:29 PM

Title: Using Python's __le__() function to define a less than or equal comparison of two objects In Python, we can define comparison operations between objects by using special methods. One of them is the __le__() function, which is used to define less than or equal comparisons. The __le__() function is a magic method in Python and is a special function used to implement the "less than or equal" operation. When we compare two objects using the less than or equal operator (&lt;=), Python

What should I pay attention to when a C++ function returns an object? What should I pay attention to when a C++ function returns an object? Apr 19, 2024 pm 12:15 PM

In C++, there are three points to note when a function returns an object: The life cycle of the object is managed by the caller to prevent memory leaks. Avoid dangling pointers and ensure the object remains valid after the function returns by dynamically allocating memory or returning the object itself. The compiler may optimize copy generation of the returned object to improve performance, but if the object is passed by value semantics, no copy generation is required.

See all articles