javascript中五种常见的DOM方法

时间:2022-07-27 18:23:26

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>