透過 document.getElementById() 拿到元素之後,就能直接用「物件.屬性」的寫法讀取或修改它的屬性,這是前端最基礎也最高頻的操作之一。
完整實例如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
</head>
<body>
<input type="text" value="我中獎了,中了一個億" id="mytext" />
<script language="javascript">
/*
* 1、取得 id 為 mytext 的 value 屬性值
* 2、取得 id 為 mytext 的 type 屬性值
*/
var txtElement = document.getElementById('mytext');
// 用「物件.屬性」的方式存取
alert(txtElement.value);
alert(txtElement.type);
</script>
</body>
</html>
重點只有一句:先選到元素,再透過屬性存取器讀寫。像 value、type、href、src 這類標準屬性都能直接這樣操作;若是自訂屬性,則改用 getAttribute() 與 setAttribute() 會更合適。