HTML教程-HTML ID

id属性用于指定 HTML 文档元素的唯一 ID。它分配CSS和JavaScript用于执行某些任务的唯一标识符。
注意:在层叠样式表 (CSS) 中,我们可以使用 # 符号后跟 id 轻松选择具有特定 id 的元素。
注意:JavaScript 可以使用 getElementById() 方法访问具有给定 ID 的元素。
句法
<tag id="value">
例1:下面的例子描述了如何在CSS文档中使用id属性:
<!DOCTYPE html>
<html>
<head>
<title>
Example of Id attribute in CSS
</title>
<style>
#Cars {
padding: 40px;
background-color: lightblue;
color: black;
text-align: center;
}
#Bikes
{
padding: 50px;
background-color: lightGreen;
text-align: center;
}
</style>
</head>
<body>
<p> Use CSS to style an element with the id: </p>
<h1 id="Cars"> Cars </h1>
<h1 id="Bikes"> Bikes </h1>
</body>
</html>
输出:
示例 2:以下示例描述了如何在 JavaScript 中使用 ID 属性。
<!DOCTYPE html>
<html>
<head>
<title> Date Attribute </title>
<script>
function viewdate() {
var x = document.getElementById("dob").value;
document.getElementById("demo").innerHTML = x;
</script>
</head>
<body>
Employee Name: <input type="text" placeholder="Your Good name"/>
<br>
<br>
Date of Joining:
<input type="date" id="dob">
<br>
<button onclick="viewdate()"> Submit
</button>
<br>
<h2 id="demo"> </h2>
</body>
</html>
输出: