DOM Attribute 学习笔记
什么是 DOM Attribute
DOM Attribute(文档对象模型属性)是 HTML 元素中的属性,如id、class、src 等等。这些属性可以通过 JavaScript 来获取和修改元素的属性值。
获取 DOM Attribute 值
可以使用 getAttribute() 方法来获取 DOM Attribute 的值,语法如下:
javascriptCopy Codeelement.getAttribute(attributeName)
其中 element 表示要获取 Attribute 的元素对象,attributeName 表示要获取的属性名称。
示例:
htmlCopy Code<img src="example.jpg" id="example">
javascriptCopy Codeconst image = document.querySelector('#example');
const src = image.getAttribute('src');
console.log(src); // 输出 example.jpg
修改 DOM Attribute 值
可以使用 setAttribute() 方法来修改 DOM Attribute 的值,语法如下:
javascriptCopy Codeelement.setAttribute(attributeName, attributeValue)
其中 element 表示要修改 Attribute 的元素对象,attributeName 表示要修改的属性名称,attributeValue 表示要设置的属性值。
示例:
htmlCopy Code<img src="example.jpg" id="example">
javascriptCopy Codeconst image = document.querySelector('#example');
image.setAttribute('src', 'new-example.jpg');
删除 DOM Attribute
可以使用 removeAttribute() 方法来删除 DOM Attribute,语法如下:
javascriptCopy Codeelement.removeAttribute(attributeName)
其中 element 表示要删除 Attribute 的元素对象,attributeName 表示要删除的属性名称。
示例:
htmlCopy Code<img src="example.jpg" id="example">
javascriptCopy Codeconst image = document.querySelector('#example');
image.removeAttribute('src');
以上就是 DOM Attribute 的基本用法。