HTML DOM id 属性
htmlweb developmentfront end technology更新于 2025/5/31 16:12:17
HTML DOM id 属性返回并允许我们设置 HTML 元素的 id。
语法
以下是语法 −
1. 返回 id
object.id
2. 设置 id
object.id=”value”
这里,"value"代表元素的 id。
示例
让我们看一个 id 属性的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
p{
background-color:#347924;
color:#fff;
padding:8px;
}
.show{
margin:8px;
color:#347924;
font-size:18px;
font-weight:bold;
}
</style>
</head>
<body>
<h1>id property Example</h1>
<p id="Awesome-para">This is a paragraph with some text and this para has an id "Awesome-para"</p>
<button onclick="getId()">Show Id</button>
<button onclick="changeId()">Change Id</button>
<div class="show"></div>
<script>
function getId() {
var paraId = document.querySelector('p').id;
document.querySelector(".show").innerHTML = paraId;
}
function changeId() {
document.querySelector('p').id = "ID-Changed";
document.querySelector(".show").innerHTML = 'new id is "ID-Chaged"';
}
</script>
</body>
</html>
输出
这将产生以下输出 −

点击"显示 ID"按钮显示绿色段落的 ID。

现在,点击"更改 ID"按钮,将绿色段落的 ID 从"Awesome-para"更改为"ID-Changed"。

我们也可以在"检查元素"下进行检查 −

相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

