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>

立即测试

输出:

HTML ID属性

示例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>

立即测试

输出:

HTML ID属性

浏览器支持

Element Chrome IE Firefox Opera Safari
<id> Yes Yes Yes Yes Yes

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_49830.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?