JavaScript 中 getAttribute 与 setAttribute 方法详解

作者:流萤

时间:2026-10-27

浏览:260

本文介绍JavaScript中用于操作HTML元素属性的两个核心方法:getAttribute和setAttribute。通过具体代码示例,演示如何获取元素的指定属性值,以及如何动态修改或添加属性。该方法适用于需要动态交互的Web开发场景,如点击按钮后更新元素标题属性。

文章目录

JavaScript 中 getAttribute 与 setAttribute 方法详解

在JavaScript中,getAttribute方法用于获取指定HTML元素的属性值,而setAttribute方法则用于设置或修改元素的属性。

具体实现代码如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script language="JavaScript">
function change() {
var input = document.getElementById("li1");
alert(input.getAttribute("title"));
input.setAttribute("title", "mgc");
alert(input.getAttribute("title"));
            }
</script>
</head>
<body>
<ul id="u">
<li id="li1" title="hello">Magci</li>
<li>J2EE</li>
<li>Haha!</li>
</ul>
<input type="button" value="Change" onClick="change();" />
</body>
</html>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章