<html>
<head>
<title>DOM四个方法</title>
<script type="text/javascript">
function method4Test() {
//document.write(typeof document.getElementById("h1's id1"));
var items = document.getElementsByTagName("h1");
document.write(items.length);
document.write(items[0].getAttribute("title"));
items[0].setAttribute("title", "New Title!");
document.write(items[0].getAttribute("title"));
}
</script>
</head>
<body onload="method4Test()">
<h1 title="h1's title1">H1.t1</h1>
<h1 title="h1's title2">H1.t2</h1>
<h1 id="h1's id1">H1.id1</h1>
<h1 id="h1's id2">H1.id2</h1>
</body>
</html>为何之后的两个title没有打出来?现在的结果是 4        把注释的那句弄回来结果是  object0   但是这段JS放到body内h1标签下部 却可以正确运行

解决方案 »

  1.   

    用document.write的话把原有body中的内容冲掉了<html>
        <head>
            <title>DOM四个方法</title>
            <script type="text/javascript">
                function method4Test() {
                    //document.write(typeof document.getElementById("h1's id1"));
                    var items = document.getElementsByTagName("h1");
                    alert(items.length);
                    alert(items[0].getAttribute("title"));
                    items[0].setAttribute("title", "New Title!");
                    alert(items[0].getAttribute("title"));
                }
            </script>
        </head>
        <body onload="method4Test()">
            <h1 title="h1's title1">H1.t1</h1>
            <h1 title="h1's title2">H1.t2</h1>
            <h1 id="h1's id1">H1.id1</h1>
            <h1 id="h1's id2">H1.id2</h1>
        </body>
    </html>