And use getAttribute to get some characteristics of node elements, use setAttribute to modify the attributes of some nodes.
Below we will introduce some DOM methods using javascript to change the architecture of web pages.
The content of this blog blog:
1. Traditional technology: document.write; innerHTML.
2. In-depth analysis of DOM methods: creatElement, createTextNode, appendChild, insertBefor.
1. The traditional definition method
document.write method:
Example 1:
<html> <head> <meta charset="utf-8" /> <title>Test</title> </head> <body> <script> document.write("<p>This is inserted</p>")<! --Write the page using the document.write method--> </script> </body> </html>
Example 2:
function insertP(text){ var str= "<p>" str += text str += "</p>" //Construct "p" tag and its content by concatenating strings document.write(str) }
Save the function in example.js.
<html> <head> <meta charset="utf-8"/> <title>Test</title> </head> <body> <script src="example.js"> </script> </body> </html>
innerHTML method:
Almost all browsers today support the innerHTML method, which can be used to read and write a given HTML content. Below
we will introduce some of its usage.
<body> <div id="testdiv"><!--Define div tag--> <p>This is<em>my</em>content</p> </div> </body>
window.onload=function(){ var testdiv = document.getElementById("testdiv") alert(testdiv.innerHTML) }
The output result is:
=><p>This is<em>my</em>content</p>
2. DOM method
createElement(nodeName) //Create label label createTextNode(text) //Create a text label parent.appendChild(child) //Insert the child element into the parent element
Create p tag and check nodeName and nodeType
window.onload=function(){ var para=document.creatElement("p") info ="nodeName: " info+=para.nodeName info+=" nodeType: " info+=nodeType alert(info) }
The output is:
=>nodeName: p nodeType: 1
appendChild method:
create a p tag and insert it into the div tag whose id is testdiv
var para=document.creatElement("p") //Create p tag var testdiv=document.getElementBId("testdiv") //Get the div tag whose Id is testdiv testdiv.appendChild(para) //Insert the tag into the div tag
createTestNode method:
create a text element and insert it into the p tag and insert the constructed p tag into the div tag
window.onload=function(){ var para=document.createElement("p") var txt= document.creteTestNode("Hellow World!") para.appendChild(txt) var testdiv=document.getElementById("testdiv") testdiv.appendChild(para) }
The above is to modify and add tags and text content in html using traditional methods and DOM methods respectively.