码迷,mamicode.com
首页 > 编程语言 > 详细

javascript中五种常见的DOM方法

时间:2015-09-21 23:44:20      阅读:435      评论:0      收藏:0      [点我收藏+]

标签:

getElementById将返回一个与那个有着给定id属性值的元素节点对应的对象。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<h1>What to buy</h1>
<p title="a gentle reminder">Don‘t forget to buy this stuff.</p>
<ul id="purchase">
<li>A tin of beans</li>
<li class="sale">Cheese</li>
<li class="sale important">Milk</li>
</ul>
<script>
alert(typeof document.getElementById("purchase"));
</script>
</body>
</html>

getElementsByTagName方法返回一个对象数组,每个对象分别对应着文档里有着给定标签的一组元素。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<h1>What to buy</h1>
<p title="a gentle reminder">Don‘t forget to buy this stuff.</p>
<ul id="purchase">
<li>A tin of beans</li>
<li class="sale">Cheese</li>
<li class="sale important">Milk</li>
</ul>
<script>
for(var i=0;i<document.getElementsByTagName("li").length;i++){
alert(typeof document.getElementsByTagName("li")[i]);
}
</script>
</body>
</html>

getElementsByClassName( HTML5) ,只接受一个参数,也就是类名,返回一个具有相同类名的元素的数组

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<h1>What to buy</h1>
<p title="a gentle reminder">Don‘t forget to buy this stuff.</p>
<ul id="purchase">
<li>A tin of beans</li>
<li class="sale">Cheese</li>
<li class="sale important">Milk</li>
</ul>
<script>
alert(document.getElementsByClassName("sale important").length);
</script>
</body>
</html>

getAttribute是一个函数,通过一个参数的名字的追加,可以获得此参数的值   而与之对应的setAttribute可以通过两个参数来设立需要被赋值的参数的名字和值

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<h1>What to buy</h1>
<p title="a gentle reminder">Don‘t forget to buy this stuff.</p>
<ul id="purchase">
<li>A tin of beans</li>
<li class="sale">Cheese</li>
<li class="sale important">Milk</li>
</ul>
<script>
var paras=document.getElementsByTagName("p");
for(var i=0;i<paras.length;i++){
var title_text=paras[i].getAttribute("title");
if(title_text){
paras[i].setAttribute("title","brand new title text");
alert(paras[i].getAttribute("title"));
}
}
</script>
</body>
</html>

javascript中五种常见的DOM方法

标签:

原文地址:http://www.cnblogs.com/daochong/p/4827543.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!