querySelectorAll、document.write、setInterval 方法的使用

 

一、querySelectorAll方法

<!DOCTYPE html>
<html>
<body>
    <p>Hello World!</p>
    <p class="intro">index 0</p>
    <p class="intro">index 1</p>
    <p id="result"></p>

    <script>
        var x = document.querySelectorAll("p.intro");
        document.getElementById("result").innerHTML = "the result is " + x[0].innerHTML;
    </script>
</body>
</html>

此querySelectorAll方法提供類似css selector語法來操作DOM。

 

二、document.write方法

<!DOCTYPE html>
<html>
<body>
    <script>
        document.write("<p>aaa</p>");
        document.write("<p>bbb</p>");
        document.close();
    </script>
</body>
</html>

document.write方法可以開始輸出串流,將原本頁面直接覆寫成指定的HTML內容,

使用document.write方法之後,最後記得把輸出串流給關起來。

 

三、setInterval方法

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
</head>
<body>
    <script>
        function show() {
            document.write(Date());
            document.close();
        }

        //表示每1000ms執行一次show function
        setInterval(show, 1000);
    </script>
</body>
</html>

 

四、更多document可用屬性請參考

Property Description DOM
document.anchors Returns all <a> elements that have a name attribute 1
document.applets Returns all <applet> elements (Deprecated in HTML5) 1
document.baseURI Returns the absolute base URI of the document 3
document.body Returns the <body> element 1
document.cookie Returns the document's cookie 1
document.doctype Returns the document's doctype 3
document.documentElement Returns the <html> element 3
document.documentMode Returns the mode used by the browser 3
document.documentURI Returns the URI of the document 3
document.domain Returns the domain name of the document server 1
document.domConfig Obsolete. Returns the DOM configuration 3
document.embeds Returns all <embed> elements 3
document.forms Returns all <form> elements 1
document.head Returns the <head> element 3
document.images Returns all <img> elements 1
document.implementation Returns the DOM implementation 3
document.inputEncoding Returns the document's encoding (character set) 3
document.lastModified Returns the date and time the document was updated 3
document.links Returns all <area> and <a> elements that have a href attribute 1
document.readyState Returns the (loading) status of the document 3
document.referrer Returns the URI of the referrer (the linking document) 1
document.scripts Returns all <script> elements 3
document.strictErrorChecking Returns if error checking is enforced 3
document.title Returns the <title> element 1
document.URL Returns the complete URL of the document 1