HTML DOM hasAttributes() 方法
htmlweb developmentfront end technology更新于 2025/9/24 6:36:17
HTML DOM hasAttributes() 方法检查元素是否具有任何属性。如果元素包含任何属性,则返回 true;如果不包含,则返回 false。如果在元素节点以外的任何其他节点上调用此方法,则返回值始终为 false。
语法
以下是 hasAttribbutes() 方法的语法 −
node.hasAttributes()
示例
让我们来看一个 hasAttributes() 方法的示例 −
<!DOCTYPE html>
<html>
<body>
<h1>hasAttributes() example</h1>
<p>This paragraph has no attributes</p>
<button onclick="containsAttr()">CHECK</button>
<p id="Sample">The paragraph above hasAttribute value : </p>
<script>
function containsAttr() {
var p = document.getElementsByTagName("P")[0];
document.getElementById("Sample").innerHTML+=p.hasAttributes();
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击"检查"按钮后 −

在上面的例子中 −
我们创建了一个没有关联属性的段落 −
<p>This paragraph has no attributes</p>
然后,我们创建了 CHECK 按钮,当用户点击时,它会执行 checkAttr() 方法 −
<button onclick="containsAttr()">CHECK</button>
containsAttr() 方法使用 getElementsByTagName() 方法获取第一个 <p> 元素,并使用索引获取第一个元素并将其赋值给变量 p。然后,它对变量 p 调用 hasAttributes() 方法并返回 false,因为第一个 <p> 元素没有属性。此值通过其 innerHTML 属性附加到 id 为 “Sample” 的段落中:
function containsAttr() {
var p = document.getElementsByTagName("P")[0];
document.getElementById("Sample").innerHTML+=p.hasAttributes();
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

