html dom對象getElementById()方法

來源:互聯網
上載者:User

標籤:

定義和用法

getElementById() 方法可返回對擁有指定 ID 的第一個對象的引用。

文法
document.getElementById(id)
說明

HTML DOM 定義了多種尋找元素的方法,除了 getElementById() 之外,還有 getElementsByName() 和 getElementsByTagName()。

不過,如果您需要尋找文檔中的一個特定的元素,最有效方法是 getElementById()。

在操作文檔的一個特定的元素時,最好給該元素一個 id 屬性,為它指定一個(在文檔中)唯一的名稱,然後就可以用該 ID 尋找想要的元素。

執行個體例子 1
<html><head><script type="text/javascript">function getValue()  {  var x=document.getElementById("myHeader")  alert(x.innerHTML)  }</script></head><body><h1 id="myHeader" onclick="getValue()">This is a header</h1><p>Click on the header to alert its value</p></body></html>
例子 2

getElementById() 是一個重要的方法,在 DOM 程式設計中,它的使用非常常見。我們為您定義了一個工具函數,這樣您就可以通過一個較短的名字來使用 getElementById() 方法了:

function id(x) {  if (typeof x == "string") return document.getElementById(x);  return x;  }

上面這個函數接受元素 ID 作為它們的參數。對於每個這樣的參數,您只要在使用前編寫 x = id(x) 就可以了。

html dom對象getElementById()方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.