HTML - DOM Document createAttribute() 方法



HTML DOM document createAttribute() 方法用於使用 JavaScript 為 HTML 元素建立具有特定名稱的屬性,並返回 Attr 物件。

語法

document.createAttribute(name);

引數

它接受一個必需的引數,如下所示。

引數 描述
name 它表示要建立的屬性的名稱。對於無效名稱,它會丟擲 InvalidCharacterError。無效名稱包括以數字、連字元開頭或包含除字母數字字元、下劃線、連字元或句點之外的其他字元。

返回值

它返回使用 createAttribute() 方法建立的節點。

HTML DOM Document 'createAttribute()' 方法示例

以下是一些說明 createAttribute() 方法用法的示例。

向錨點標籤新增 href

在以下示例中,href 新增到錨點標籤。

<!DOCTYPE html>
<html lang="en">
<head>
   <title>HTML DOM Document createAttribute() Method</title>
</head>
<body>
    <h3>HTML DOM Document createAttribute() Method</h3>
    <a id="attr">Welcome to TutorialsPoint</a>
    <br>
    <button onclick="fun()">Click me</button>
    <script>
        function fun(){
            let x=document.createAttribute("href");
            x.value="https://tutorialspoint.tw/index.htm"
            document.getElementById("attr").setAttributeNode(x);
        }
    </script>
</body>
</html>

向段落新增類

在以下示例中,我們建立了一個類並將其新增到一個 <p> 以更改文字的字型顏色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Document createAttribute() Method</title>
    <style>
        .classone {
            color: #04af2f;
        }
    </style>
</head>
<body>
    <h3>HTML DOM Document createAttribute() Method</h3>
    <p id="attr">Welcome to TutorialsPoint</p><br>
    <button onclick="fun()">Click me</button>
    <script>
        function fun() {
            let x = document.createAttribute("class");
            x.value = "classone"
            document.getElementById("attr").setAttributeNode(x);
        }
    </script>
</body>
</html>

向段落新增樣式

在以下示例中,我們向一個 <p> 添加了樣式以更改文字的字型顏色。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM Document createAttribute() Method</title>
    <style>
        .classone {
            color: #04af2f;
        }
    </style>
</head>
<body>
    <h3>HTML DOM Document createAttribute() Method</h3>
    <p id="attr">Welcome to TutorialsPoint</p><br>
    <button onclick="fun()">Click me</button>
    <script>
        function fun() {
            let x = document.createAttribute("style");
            x.value = "color :#04af2f";
            document.getElementById("attr").setAttributeNode(x);
        }
    </script>
</body>
</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
createAttribute() 是 1 是 12 是 44 是 1 是 12.1
廣告