DOM及getElementById等常用的4个方法

本文介绍DOM(document object model)的基本概念及四个常用方法:getElementById(), getElementsByTagName(), getAttribute(), setAttribute()。并通过一个图片展示的例子详细展示了这些方法的具体应用。

DOM是document object model的缩写。其中,

D:当创建了一个网页,并加载到浏览器时,就产生了DOM,它将为网页内容创建一个文档。

O:文档中的每个节点都是一个对象,比如元素节点,属性节点,文本节点。

M:模型,即文档以何种形式显示出来。


DOM中常用的方法有4个:

  • getElementById(),通过id来来获取对象
  • getElementsByTagName(),通过标签名字来获取对象
  • getAttribute()
  • setAttribute()

有几点需要注意:
1、前两者有document来调用,后两者由节点对象来调用
2、getElementsByTagName()返回的是对象数组

下面给出一个小例子来说明以上几个方法的使用:
<html>
<head>
<meta http-equiv = "content-type" content = "text/html; charset = utf-8" />
<title>Image Gallery</title>
<script language = "javascript">
function showPic(whichPic)
{
	var source = whichPic.getAttribute("href");			//获得源
	
	var holder = document.getElementById("placeholder");
	holder.setAttribute("src", source);		
}

function countBodyChildren()
{
	var body_element = document.getElementsByTagName("li");
	alert(body_element.length);
}
window.onload = countBodyChildren;
</script>
</head>
<body>
	<h1>Snapshots</h1>
	<ul>
		<li>
			<a href = "1.jpg" title = "picture1" onclick = "showPic(this); return false;">picture1			</a>
		</li>
		<li>
			<a href = "2.jpg" title = "picutre2" onclick = "showPic(this); return false;">picture2			</a>
		</li>
		<li>
			<a href = "3.jpg" title = "picture3" onclick = "showPic(this); return false;">picture3			</a>
		</li>
	</ul>
	<img id = "placeholder" src = "4.jpg" alt = "my placeholder" />
	<p id = "description">choose an iamge</p>
</body>
</html>
说明:
1、四张图片,命名为1.jpg,2.jpg,3.jpg,4,jpg,与所创建的html文档放在一个文件夹里
2、上述代码要实现的功能是,有三个链接,点击一个,就用其对应的图片来取代用作占位符的图片4


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值