访问 JavaScript HTML 文档的所有元素
<html>
<head>
<title>DOM文档对象模型 --访问 JavaScript HTML 文档的所有元素</title>
<script>
//HTML DOM 模型被构造为对象的树
//节点分3种: 1.元素节点(标签)--<div>标签 ; 2.文本节点--标签内的文本; 3.属性节点--标签的属性,如id
//DOM必须等到HTML加载完后才能获取; 所以方法一: script 脚本放到最下面; 方法二: onload事件加载HTML。 window.onload=function(){ ...}//
window.onload=function(){
document.getElementById('test').innerHTML='lllll';
};
function displayDate()
{
document.getElementById("test").innerHTML=Date();
}
</script>
</head>
<body>
<div id='test'> 测试</div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
<p>你好</p>
<button type="button" onclick=displayDate()>点击这里</button>
<button type="button" onclick="document.getElementById('test').style.color='red'">点击这里</button>
<input type="button" value="隐藏文本" onclick="document.getElementById('test').style.visibility='hidden'" />
<input type="button" value="显示文本" onclick="document.getElementById('test').style.visibility='visible'" />
<h1 onclick="this.innerHTML='谢谢!'">请点击该文本</h1>
</body>
</html>
onload 和 onunload 事件会在用户进入或离开页面时被触发
<html>
<head>
<title>DOM文档对象模型 --访问 JavaScript HTML 文档的所有元素</title>
<script>
//onload 和 onunload 事件会在用户进入或离开页面时被触发
function checkcookies(){
if(navigator.cookieEnabled == true){
alert('cookie已启动');
}
else{
alert('cookie未启动');
}
}
function uppercase(){
var v = document.getElementById("myid");
v.value = v.value.toUpperCase();
}
function mover( ojb ){
ojb.innerHTML='11111';
}
function mout( ojb ){
ojb.innerHTML='<strong>2222</strong>';
}
function changecolor(obj,color){
obj.style.background=color;
}
document.write('pp.firstChild');
</script>
</head>
<body onload="checkcookies()">
<input type='text' id='myid' onchange='uppercase()'>
<input type='text' id='myid' onfocus='changecolor(this,"red")'>
<div onmouseover='mover(this)' onmouseout='mout(this)'>llll</div>
<div id='box' title='标题' class='bbb'>
<p>div1</p>
<p>div2</p>
<p>div3</p>
</div>
</body>
</html>
节点操作
<html>
<head>
<title>DOM文档对象模型 --节点操作</title>
<script>
window.onload= function(){
var b=document.getElementById('box');
var p = document.createElement('p');//创建节点
//b.appendChild(p);
var text=document.createTextNode('测试');
p.appendChild(text);//文本添加到p节点
//b.appendChild(text);//文本添加到p节点
//b.parentNode.insertBefore(p,b);//返回父节点添加
//p.appendChild(text);//文本添加到p节点
insertafter(p,b);
};
//span前面添加节点
function insertafter( newelement, targetelement){
var parent = targetelement.parentNode;
//span节点的前面添加即可,span的获取用nextSibling
parent.insertBefore(newelement,targetelement.nextSibling);
}
</script>
</head>
<body >
<div id='box' title='标题' class='bbb'>
<p>div1</p>
<p>div2</p>
</div>
<span>你好</span>
</body>
</html>