JavaScript 函数 'getAttribute' 用于获取指定元素的属性值。它接受一个参数,即要获取的属性名,然后返回对应的属性值。

使用方法如下:

element.getAttribute(attributeName)

其中,'element' 是要获取属性的元素,'attributeName' 是要获取的属性名。

例如,如果有一个 'div' 元素如下:

<div id='myDiv' class='container' data-info='some data'>Hello, World!</div>

我们可以通过 'getAttribute' 来获取它的属性值:

var div = document.getElementById('myDiv');

var id = div.getAttribute('id');
console.log(id); // 输出:myDiv

var className = div.getAttribute('class');
console.log(className); // 输出:container

var dataInfo = div.getAttribute('data-info');
console.log(dataInfo); // 输出:some data

注意,'getAttribute' 返回的是一个字符串,如果指定的属性不存在,则返回 'null'。

JavaScript getAttribute 函数详解:获取元素属性值

原文地址: https://www.cveoy.top/t/topic/o95w 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录