HTML - DOM HTMLCollection item() 方法



HTML DOM HTMLCollection **item()** 方法返回 HTMLCollection 中位於指定索引處的元素。

語法

HTMLCollection.item(index);
// or
HTMLCollection[index];

引數

此方法接受如下所示的單個引數。

引數 描述
索引 它表示要返回的索引。索引從 0 開始。

返回值

它返回指定索引處的元素,如果索引超出範圍則返回 null。

HTML DOM HTMLCollection 'item()' 方法示例

以下示例說明了 HTMLCollection item() 方法的不同用法。

獲取第一個指令碼元素的內容

在此示例中,我們將使用 item() 方法獲取第一個指令碼元素的內容。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>DOM HTMLCollection item() Method</title>
</head>
<body>
    <script>document.getElementById("s1").innerHTML = "First Script."</script>
    <script>document.getElementById("s2").innerHTML = "Second Script."</script>
    <script>document.getElementById("s3").innerHTML = "Third Script."</script>
    <p>Click to get content of first script element.</p>
    <button onclick="fun()">Click me</button>
    <p id="scripts"></p>
    <script>
        function fun() {
            let x = document.scripts.item(0).text;
            document.getElementById("scripts").innerHTML = x;
        }
    </script>
</body>
</html>

獲取第一個指令碼元素內容的替代方法

在此示例中,我們使用了上面示例中使用 HTMLCollection[index] 方法的替代方法。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>DOM HTMLCollection item() Method</title>
</head>
<body>
    <script>
        document.getElementById("s1").innerHTML = "This is first Script."
    </script>
    <script>
        document.getElementById("s2").innerHTML = "This is second Script."
    </script>
    <script>
        document.getElementById("s3").innerHTML = "This is third Script."
    </script>
    <p>Click to get content of first script element.</p>
    <button onclick="fun()">Click me</button>
    <p id="scripts"></p>
    <script>
        function fun() {
            let x = document.scripts[0].text;
            document.getElementById("scripts").innerHTML = x;
        }
    </script>
</body>
</html> 

更改段落樣式

在以下示例中,我們將第一個段落的文字背景顏色更改為綠色,其餘更改為紅色,字型顏色更改為白色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>DOM HTMLCollection item() Method</title>
</head>
<body>
    <p>
        Click to change the background color 
        of following paragraphs.
    </p>
    <button onclick="fun()">Click me</button>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <script>
        function fun() {
            let x = document.getElementsByTagName("p");
            for (let i = 0; i < x.length; i++) {
                x[i].style.color = "white";
                x[0].style.backgroundColor = "#04af2f";
                x[i + 1].style.backgroundColor = "red";
            }
        }
    </script>
</body>
</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
item() 是 1 是 12 是 1 是 1 是 12.1
html_dom_htmlcollection_reference.htm
廣告