HTML DOM allows JavaScript to change the content of HTML elements.
document.write()
In JavaScript, document.write() can be used to write content directly to the HTML output stream.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <head> <body> <p>当前时间是: <script type="text/javascript"> document.write("<strong>"+(new Date()).toString()+"</strong>"); </script> </p> </body> </html>
Never use document.write() after the document has been loaded. This will overwrite the document.
innerHTML
The innerHTML attribute is used to set or return the HTML between specified tags content.
Syntax: document.getElementById(id).innerHTML=new HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <p id="p1">Hello World!</p> <script> document.getElementById("p1").innerHTML="新文本!"; </script> <p>以上段落通过脚本修改文本。</p> </body> </html>
Change HTML attributes
Syntax: document.getElementById(id).attribute=New attribute The value
attribute is an attribute node. Each DOM element has a corresponding attributes attribute to store all attribute nodes. Attributes is a class The container of an array, to be precise, is NameNodeMap. In short, it is a container similar to an array but different from an array. Each numeric index of attributes stores an attribute node in the form of a name-value pair (name="value").
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> var dir = "left"; function setDir() { dir = (dir=="left") ? "right" : "left"; document.getElementById( "Mar" ).direction = dir; } </script> </head> <body> <marquee id="Mar">欢迎光临!</marquee> <p><button onclick="setDir()">改变方向</button></p> </body> </html>