ZetCode

JavaScript getAttributeNames

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 element.getAttributeNames 方法。此方法返回元素的所有属性名称的数组。它对于动态检查和处理元素属性非常有用。

基本定义

getAttributeNames 方法返回一个字符串数组,其中包含指定元素的所有属性名称。这包括标准的 HTML 属性和自定义数据属性。

与单独访问属性不同,此方法提供了一个完整的列表。当您需要检查元素的所有属性而不知道其名称时,它特别有用。

基本 getAttributeNames

此示例演示了如何从简单的 div 元素获取所有属性名称。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic getAttributeNames</title>
</head>
<body>

<div id="content" class="main" data-info="sample">Example div</div>

<script>
    const element = document.querySelector('div');
    const attributes = element.getAttributeNames();
    console.log(attributes); // ["id", "class", "data-info"]
</script>

</body>
</html>

在此基本示例中,我们有一个具有三个属性的 div 元素。JavaScript 代码使用 getAttributeNames 检索所有属性名称,并将它们记录到控制台。

该方法返回一个包含“id”、“class”和“data-info”的数组。这表明了它是如何捕获标准属性和自定义数据属性的。

处理表单元素

此示例展示了如何检查表单输入元素的属性。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Form Element Attributes</title>
</head>
<body>

<input type="text" id="username" 
       placeholder="Enter name" required data-validation="strict">

<script>
    const input = document.getElementById('username');
    const attributes = input.getAttributeNames();
    
    attributes.forEach(attr => {
        console.log(`${attr}: ${input.getAttribute(attr)}`);
    });
</script>

</body>
</html>

这里我们有一个具有多个属性的 input 元素。代码获取所有属性名称,然后遍历它们以记录名称和值。

这演示了如何将 getAttributeNamesgetAttribute 结合起来以编程方式检查元素的的所有属性。

检查特定属性

此示例演示了如何检查元素是否具有特定属性。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Attribute Checking</title>
</head>
<body>

<button id="submitBtn" disabled data-action="save">Submit</button>

<script>
    const button = document.getElementById('submitBtn');
    const attributes = button.getAttributeNames();
    
    console.log('Has disabled attribute:', attributes.includes('disabled'));
    console.log('Has data-action attribute:', attributes.includes('data-action'));
    console.log('Has non-existent attribute:', attributes.includes('aria-label'));
</script>

</body>
</html>

在此示例中,我们检查按钮元素是否具有特定属性。includes 方法用于 getAttributeNames 返回的数组。

此技术对于功能检测或基于元素属性的条件逻辑很有用。它比直接检查属性值更可靠。

动态属性检查

此示例显示了如何在属性更改后动态检查属性。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Attributes</title>
</head>
<body>

<div id="dynamicDiv">Watch my attributes</div>
<button onclick="addAttribute()">Add Attribute</button>
<button onclick="showAttributes()">Show Attributes</button>

<script>
    function addAttribute() {
        const div = document.getElementById('dynamicDiv');
        const count = div.getAttributeNames().length;
        div.setAttribute(`data-attr-${count}`, `value-${count}`);
    }
    
    function showAttributes() {
        const div = document.getElementById('dynamicDiv');
        console.log(div.getAttributeNames());
    }
</script>

</body>
</html>

这里我们有一个 div 和两个按钮。一个按钮向 div 添加新属性,另一个按钮显示所有当前属性。

这表明了如何使用 getAttributeNames 来跟踪元素属性的动态变化。该方法始终返回属性的当前状态。

按属性比较元素

此示例展示了如何根据属性比较两个元素。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Attribute Comparison</title>
</head>
<body>

<div class="box" id="box1" data-color="red">Box 1</div>
<div class="box" id="box2" data-color="blue">Box 2</div>

<script>
    const box1 = document.getElementById('box1');
    const box2 = document.getElementById('box2');
    
    const box1Attrs = box1.getAttributeNames();
    const box2Attrs = box2.getAttributeNames();
    
    // Check if they have the same attribute names (order doesn't matter)
    const sameAttributes = box1Attrs.length === box2Attrs.length &&
                         box1Attrs.every(attr => box2Attrs.includes(attr));
    
    console.log('Same attributes:', sameAttributes);
</script>

</body>
</html>

在此示例中,我们比较两个 div 元素,以查看它们是否具有相同的属性名称集,而忽略其值。

当您需要验证元素是否遵循特定的属性模式或在实现自定义差异算法时,此技术可能很有用。

来源

MDN getAttributeNames 文档

在本文中,我们展示了如何在 JavaScript 中使用 element.getAttributeNames。此方法为 Web 开发中处理和检查元素属性提供了强大的功能。

作者

我叫 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 JS DOM 教程