HTML - DOM 文件 anchors 屬性



HTML DOM document 的 **anchors** 屬性是一個只讀屬性,它列出了文件中所有具有 name 屬性的 **<a>** 標籤。此屬性已 **棄用**。

它列出了具有 name 屬性的錨點標籤,並且由於 name 屬性在 HTML 5 中不再受支援,因此不再推薦使用 anchors 屬性。您可以使用其替代方法 **getElementsByTagName('a')** 來獲得相同的結果。

語法

document.anchors;

返回值

它返回一個 HTML 集合,其中包含所有具有 name 屬性的 **<a>** 標籤。

HTML DOM Document 'anchors' 屬性示例

以下示例說明了 anchors 屬性的使用。

獲取錨元素的數量

在此示例中,anchors 屬性返回具有 name 屬性的 <a> 標籤的數量。

<!DOCTYPE html>
<html>
<head>
    <title>HTML DOM document anchors Property</title>
</head>
<body>
    <a name="tutorix">Tutorix</a>
    <br>
    <a name="tutorialspoint">Tutorialspoint</a>
    <br>
    <a> I am without name attribute</a>
    <p>Number of anchor tags with name attribute :</p>
    <p id="anchors"></p>
    <script>
        let num = document.anchors.length;
        document.getElementById("anchors").innerHTML =num;
    </script>
</body>
</html>

獲取錨元素數量的替代方法

在此示例中,getElementsByTagName 用作獲取錨元素數量的替代方法。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM document anchors Property</title>
</head>
<body>
    <a name="tutorix">Tutorix</a>
    <br>
    <a name="tutorialspoint">Tutorialspoint</a>
    <br>
    <a> I am without name attribute</a>
    <p>Click to get the number of anchor element.</p>
    <button onclick="fun()">Click me</button>
    <p id="anchors"></p>
    <script>
        function fun() {
            let num = document.getElementsByTagName("a").length;
            document.getElementById("anchors").innerHTML = num;
        }
    </script>
</body>
</html>

獲取第一個錨元素的內容

以下示例返回第一個 <a> 元素的內容。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM document anchors Property</title>
</head>
<body>
    <a name="tutorix">Tutorix</a>
    <br>
    <a name="tutorialspoint">Tutorialspoint</a>
    <br>
    <a> I am without name attribute</a>
    <p>Click to get the content of first anchor element.</p>
    <button onclick="fun()">Click me</button>
    <p id="anchors"></p>
    <script>
        function fun() {
            let num = document.anchors[0].innerHTML;
            document.getElementById("anchors").innerHTML = num;
        }
    </script>
</body>
</html>

獲取第一個錨元素內容的替代方法

在此示例中,getElementsByTagName 用作獲取第一個錨元素內容的替代方法。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM document anchors Property</title>
</head>
<body>
    <a name="tutorix">Tutorix</a>
    <br>
    <a name="tutorialspoint">Tutorialspoint</a>
    <br>
    <a> I am without name attribute</a>
    <p>Click to get the content of first <a> element.</p>
    <button onclick="fun()">Click me</button>
    <p id="anchors"></p>
    <script>
        function fun() {
            let num = document.getElementsByTagName("a")[0].innerHTML;
            document.getElementById("anchors").innerHTML = num;
        }
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
anchors
廣告