<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>document对象学习</title>
<!--
document对象学习:
1:document对象的概念
浏览器对外提供的支持js的用来操作HTML文档的一个对象,此对象封存的HTML文档的所有信息
2:使用document
获取HTML元素对象
直接获取方式:
通过id
通过name属性值
通过标签名
通过class属性值
间接获取方式:
父子关系
子父关系
兄弟关系
操作HTML对象的属性
操作HTML元素对象的内容和样式
操作HTML的文档结构
document操作Form元素
document操作表格
document对象实现form表单校验
-->
<script type="text/javascript">
//document获取元素
//直接方式
function testGetEleById(){
var inp=window.document.getElementById("uname");
alert(inp);
}
function testGetEleByName(){
var ips=window.document.getElementsByName("fav");
alert(ips.length);
}
//标签名
function testGetEleByTagName(){
var iop=window.document.getElementsByTagName("input");
alert(iop.length)
}
//class属性
function testGetEleByClassName(){
var inps=window.document.getElementsByClassName("commom");
alert(inps.length);
alert(inps);
}
//间接获取方式
//父子关系
function testParent(){
//获取父级元素对象
var showdiv=document.getElementById("showdiv");
//获取所有子元素对象数组
var childs=showdiv.childNodes ;
alert(childs);
}
//子父关系
function testChild(){
var inp=document.getElementById("inp");
var div=inp.parentNode;
alert(div);
}
//兄弟关系
function testBrother(){
var inp=document.getElementById("inp");
var preEle=inp.previousSibling;//弟获取兄
var nextEle=inp.nextSibling;//兄获取弟
alert(preEle+"::"+nextEle);
}
</script>
<style type="text/css">
.commom{}
#showdiv{
border: solid 1px orange;
height: 300px;
width: 300px;
}
</style>
</head>
<body>
<h3>document对象的概念和获取元素对象学习</h3>
<hr />
<input type="button" name="" id="" value="测试获取HTML元素对象--id" onclick="testGetEleById()" />
用户名:<input type="text" name="uname" id="uname" value="" /><hr />
<input type="button" name="" id="" value="测试获取HTML元素对象--name" onclick="testGetEleByName()"/>
<input type="checkbox" name="fav" id="" value="" class="commom"/>唱歌
<input type="checkbox" name="fav" id="" value="" />打游戏
<input type="checkbox" name="fav" id="" value="" />健身
<input type="checkbox" name="fav" id="" value="" />睡觉
<input type="button" name="" id="" value="测试获取HTML元素对象--TagName" onclick="testGetEleByTagName()" />
<input type="button" name="" id="" value="测试获取HTML元素对象--ClassName" onclick="testGetEleByClassName()"/>
<hr />
间接获取方式学习:
<input type="button" name="" id="" value="测试父子关系" onclick="testParent()" />
<div id="showdiv">
<input type="" name="" id="" value="" /><input type="" name="" id="inp" value="" />
<input type="" name="" id="" value="" />
<input type="" name="" id="" value="" />
<input type="" name="" id="" value="" />
<input type="" name="" id="" value="" />
</div>
<input type="button" name="" id="" value="测试子父关系" onclick="testChild()" />
<input type="button" name="" id="" value="测试兄弟关系" onclick="testBrother()" />
</body>
</html>