标签解读
<p title="a gentle reminder"> don't forget to buy this stuff</p>
其中p标签是元素标签, title标签是属性标签, don't forget to buy this stuff文档标签
getElementById方法
getElementById(id值)方法获取到是一个给定id的的元素节点(标签)对象
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
<title>知晓怎么使用js第一课</title>
</head>
<body>
<h1> shopping list </h1>
<h3> What want to buy </h3>
<p title="a gentle reminder"> don't forget to buy this stuff</p>
<ul id="purchases">
<li>A tin of beans</li>
<li>Cheese</li>
<li>Milk</li>
</ul>
<script type="text/javascript">
alert(document.getElementById("purchases"));
alert(typeof document.getElementById("purchases"));
</script>
</body>
</html>
getElementsByTagName方法
getElementsByTagName(tagname)方法将返回一个对象数组
alert(document.getElementsByTagName("li").length);
// 第一种写法,这里没有赋予变量
for(var i=0; i<document.getElementsByTagName("li").length; i++){
alert(document.getElementsByTagName("li")[i]);
alert(typeof(document.getElementsByTagName("li")[i]));
}
// 获取整个文档中一共有多少个标签(节点)
alert(document.getElementsByTagName("*").length);
getAttribute方法
getAttribute(attribute)方法,用来查询那个标签的属性,即这个方法适应在标签中
var oPsum = document.getElementsByTagName("p");
for (var i=0; i<oPsum.length; i++){
if (oPsum[i].getAttribute("title")!=null){
alert(oPsum[i].getAttribute("title"));
}
}
setAttribute方法
setAttribute(attribute, value)方法,该方法获取标签的属性后,更改其属性值
var oPsum = document.getElementsByTagName("p");
for (var i=0; i<oPsum.length; i++){
sTitle_text = oPsum[i].getAttribute("title");
if (sTitle_text){
alert(sTitle_text);
oPsum[i].setAttribute("title", "a new band title text");
alert(oPsum[i].getAttribute("title"));
}
}