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
广告
© . All rights reserved.