document对象
概述:浏览器对外提供的支持js操作HTML文档的一种对象,这个对象封装了HTML文档中的所有对象。当HTML文档一执行,就会创键document对象,把HTML文档中的所有信息封装到document对象中,我们要获取HTML文档中的信息,只需要操作document这个对象即可。
获取元素属性,两种方式
直接获取
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>document对象</title>
<style type="text/css">
input{
width: 100px;
height: 50px;
border-radius: 5px;
background-color: #008000;
color: white;
}
</style>
</head>
<body>
<input type="button" name="LD" id="" value="获取元素id" onclick="testGetId()"/>
<hr >
<input type="button" name="LD" id="" value="获取name" onclick="testGetName()"/>
<hr >
<input type="button" name="" id="" value="获取标签" onclick="testGetTagname()"/>
<hr >
<input type="button" name="" id="" value="获取类名" onclick="testClassNames()"/>
<hr >
<div id="uname">
</div>
<div class="LED"></div>
<input type="checkbox" name="val" id="" value="" />唱
<input type="checkbox" name="val" id="" value="" />跳
<input type="checkbox" name="val" id="" value="" />rap
<input type="checkbox" name="val" id="" value="" />打篮球
<input type="checkbox" name="val" id="" value="" />扭秧歌
<input type="checkbox" name="val" id="" value="" />二人转
</body>
<script type="text/javascript" src="../js/documentObject.js">
</script>
</html>
js代码
/*获取元素id*/
function testGetId(){
var id = document.getElementById("uname");
alert(id);
}
/*获取元素名称*/
function testGetName(){
var names = document.getElementsByName("LD");
alert(names);
}
/*获取标签名*/
function testGetTagname(){
var tagNames = document.getElementsByTagName("input");
alert(tagNames);
}
/*获取类名*/
function testClassNames(){
var classNames = document.getElementsByClassName("LED");
alert(classNames);
}
结果:
间接获取
1、父子关系
2、子父关系
3、兄弟关系
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>document对象</title>
<style type="text/css">
input{
width: 100px;
height: 50px;
border-radius: 5px;
background-color: #008000;
color: white;
}
</style>
</head>
<body>
<input type="button" name="" id="" value="测试父子关系" onclick="testParentToSon()"/>
<hr >
<input type="button" name="" id="" value="测试子父关系" onclick="testSonToParent()"/>
<hr >
<input type="button" name="" id="" value="测试兄弟关系" onclick="testBrother()"/>
<hr >
<div id="uname">
<div id="creazy">
<p id="pp"></p>
<p></p>
<p></p>
<p></p>
<p></p>
</div>
<div id="bor">
</div>
<div id="hello"></div>
</div>
<div class="LED"></div>
</body>
<script type="text/javascript" src="../js/documentObject.js">
</script>
</html>
js代码
/*父子关系*/
function testParentToSon(){
//现获取元素ID对象
var id = document.getElementById("uname");
var childs = id.childNodes;
alert(childs.length);
}
/*子父关系*/
function testSonToParent(){
//现获取元素ID对象
var id = document.getElementById("pp");
var childs = id.parentNode;
alert(childs);
}
/*兄弟关系*/
function testBrother(){
//现获取元素ID对象
var bor = document.getElementById("bor");
var gg = bor.previousElementSibling;
var dd = bor.nextElementSibling;
alert(gg+":"+dd);
}