摘要:在本教程中,您将学习如何使用 JavaScript removeAttribute()
方法从元素中删除具有指定名称的属性。
JavaScript removeAttribute() 方法简介
removeAttribute()
方法从元素中删除具有指定名称的属性。
element.removeAttribute(name);
Code language: CSS (css)
参数
removeAttribute()
接受一个参数,即要删除的属性的名称。如果属性不存在,removeAttribute()
方法将不会 引发错误。
返回值
removeAttribute()
返回 undefined
值。
使用说明
HTML 元素具有一些布尔属性。
要将布尔属性设置为 false
,您不能简单地使用 setAttribute()
方法。您必须使用 removeAttribute()
方法完全删除属性。
例如,在以下情况下,disabled
属性的值为 true
<button disabled>Save Draft</button>
<button disabled="">Save</button>
<button disabled="disabled">Cancel</button>
Code language: HTML, XML (xml)
类似地,以下 readonly
属性的值为 true
<input type="text" readonly>
<textarea type="text" readonly="">
<textarea type="text" readonly="readonly">
Code language: HTML, XML (xml)
JavaScript removeAttribute() 方法示例
以下示例使用 removeAttribute()
方法从 id 为 js
的链接元素中删除 target
属性
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS removeAttribute() Demo</title>
</head>
<body>
<a href="https://tutorial.javascript.ac.cn"
target="_blank"
id="js">JavaScript Tutorial</a>
<script>
let link = document.querySelector('#js');
if (link) {
link.removeAttribute('target');
}
</script>
</body>
</html>
Code language: HTML, XML (xml)
工作原理
- 使用
querySelector()
方法选择 id 为js
的链接元素。 - 通过在选定的链接元素上调用
removeAttribute()
来删除链接的target
属性。
摘要
- 使用
removeAttribute()
从指定元素中删除属性。 - 将布尔属性的值设置为
false
将不起作用;请改用removeAttribute()
方法。
测验
本教程对您有帮助吗?