DOM操作(上)
一.DOM
作用:DOM(Document Object Nodel)
1.document 文档 HTML文件 XML文件(标记语言)
<body>
<div>
<a>ssssss</a>
</div>
</body>
2.Object 对象(HTML元素转成的js对象)
注意:如果使用js操作HTML或XML文档,就需要先将HTML文档结构转成js对象
a、操作属性
b、操作内容
innerText内部的文本(IE能用)(非IE用textContent)
innerHTML
outerText
outerHTML外标签
表单 ----value
c、操作样式
单个操作
aobj.style.backgroundColor="red";
aobj.style.fontSize="3cm";
批量操作
className
aobj.className="test";
aobj.className+=" demo";
//aobj.className="test demo";
aobj.className="";//清除类
有了以上三点的操作之前先转成对象
转成对象的两种方式
A、标记名(li、a、ul等等 ---多个)、id名(唯一)、name(多个)、class
document中的三个方法
var objs=document.getElementsByTagName("div");
var objs=document.getElementById("one");
var objs=document.getElementsByName("two");
B、用数组获取对象
document.title=
document.body=[object]
window.frames=[object]
document.all=[object]
document.embeds=[object]//所有动画
document.scripts=[object] //所有脚本
document.applets=[object]//
document.images=[object]
document.forms=[object]
document.anchors=[object]//所有锚点<a>中带name的
document.styleSheets=[object]
document.links=[object]
有七种方式
alert(document.forms[1].username.value);//结果为lisi
alert(document.forms["frm2"].username.value);
alert(document.forms.item(1).username.value);
alert(document.forms.item("frm2").username.value);
alert(document.forms.frm2.username.value);
alert(document.frm2.username.value);
alert(document["frm2"].username.value);
例1
<html>
<head>
<style>
#alink{
width:400px
}
.test{
width:500px;
height:300px;
border:5px solid blue;
color:red;
font-size:4cm
background:yellow;
}
.demo{
width:500px;
height:300px;
}
</style>
</head>
<body>
<div></div>
<div id="one"></div>
<div name="two"></div>
<textarea id="content">mmmmmmm</textarea><br>
<input id="username" type="text" name="username" value="zhangsan"><br>
<a id="alink" href="www.souhu.com" target="_blank" title="this is a test"><b>test</b></a>
<script>
var aobj=document.getElementById("alink");//把文档变成对象
aobj.href="www.baidu.com"; //操作属性
aobj.target="_self";
aobj.title="demo demo demo";
aobj.innerText="brother";//内部的文本
aobj.innerHTML="<b>brother</b>"//结果加粗了
aobj.style.backgroundColor="red";//"-"去掉,首字母大写
aobj.style.fontSize="3cm";
aobj.className="text demo"
alert(aobj.offsetWidth);//输出400,如果style写在内部了就可以直接用aobj.width获取其值了。
alert(aobj.outerHTML);//输出结果是:包含<a>标签的所有东西
var username=document.getElementById("username");
var content=document.getElementById("content");
alert(username.value);//得到zhangsan
alert(content.value);//textarea同样用value获取其值,因为它也是表单里的一项。
</script&