1.文档对象模型DOM(Document Object Model)定义访问和处理HTML文档的标准方法。DOM将HTML文档呈现为带有元素、属性和文本的树结构(节点树)。
1. 元素节点:上图中<html>、<body>、<p>等都是元素节点,即标签。
2. 文本节点:向用户展示的内容,如<li>...</li>中的JavaScript、DOM、CSS等文本。
3. 属性节点:元素属性,如<a>标签的链接属性href="http://www.imooc.com"。
2.通过ID获取元素
语法:document.getElementById("id")
3.innerHTML属性
<h2 id="con">javascript</H2>
<script type="text/javascript">
var mychar= document.getElementById("con") ;
document.write("原标题:"+mychar.innerHTML+"<br>"); //输出原h2标签内容
mychar.innerHTML="hello word"
document.write("修改后的标题:"+mychar.innerHTML); //输出修改后h2标签内容
</script>
4.改变HTML样式
语法:(Object是获取的元素对象)Object.style.属性=新的样式
5.显示和隐藏(display属性)
Object.style.display=none(隐藏)/block(显示)
6.控制类名
语法:Object.className="类"
<style>
body{ font-size:16px;}
.one{ border:1px solid #eee;width:230px;height:50px;background:#ccc;color:red;}
.two{ border:1px solid #ccc;width:230px;height:50px;background:#9CF; color:blue; }
</style>
<body>
<p id="p1" > JavaScript使网页显示动态效果并实现与用户交互功能。</p>
<input type="button" value="添加样式">
<p id="p2" class="one">JavaScript使网页显示动态效果并实现与用户交互功能。</p>
<input type="button" value="更改外观">
<script>
function add(){
var p1=document.getElementById("p1");
p1.className="one" }
function modify(){
var p2=document.getElementById("p2");
p2.className="two" }
7.作业
1.改变颜色2.改变宽高3.隐藏内容4.显示内容5.取消设置
<style type="text/css">
body{font-size:12px;}
#txt{height:400px; width:600px; border:#333 solid 1px; padding:5px;}
p{ line-height:18px; text-indent:2em;}
</style>
<body>
<h2 id="con">JavaScript课程</H2>
<div id="txt">
<p>1. JavaScript入门篇,让不懂JS的你,快速了解JS。</p>
<p>2. JavaScript进阶篇,让你掌握JS的基础语法、函数、数组、事件、内置对象、BOM浏览器、DOM操作。</p>
</div>
<form>
<!--当点击相应按钮,执行相应操作,为按钮添加相应事件-->
<input type="button" value="改变颜色"
<input type="button" value="改变宽高"> <input type="button" value="隐藏内容"> <input type="button" value="显示内容"> <input type="button" value="取消设置">
</form>
<script type="text/javascript">
//定义"改变颜色"的函数
function col(){ txt.style.color="red" }
//定义"改变宽高"的函数
function wid(){ txt.style.width="100px"; txt.style.height="100px"
}
//定义"隐藏内容"的函数
function no(){ txt.style.display="none"}
//定义"显示内容"的函数
function ss(){ txt.style.display="block"}
//定义"取消设置"的函数
function qx(){ var rec=confirm("是否取消?")
if(rec==true){ txt.style="none" }
}
Node对象的属性
属性 类型 描述
parentNode Node 父节点 ,没有父节点返回null
childNodes NodeList 子节点
firstChild Node 第一个子节点,没有返回null
lastChild Node 最后一个子节点,没有返回null
nodeValue String 节点值
nodeName String 节点名
previousSibling Node 上一个兄弟节点
nextSibling Node 下一个兄弟节点
nodeType short 节点类型的常量
Element //表示标签 Text //表示文本内容 Type //类型
DOM操作文档
Node对象的常用方法
方法 描述
insertBefore(newchild,refchild) 在现有节点refchild之前插入节点newchild
replaceChild(newchild,oldchild) 将子节点清单中的子节点oldchild替换成newchild,
并返回oldchild节点
removeChild(oldchild) 移除已有的子节点再返回oldchild节点