JavaScript/Finding elements

簡單使用 編輯

在一個網頁:

<div id="myDiv">content</div>

在 JavaScript 中查找此元素的一種簡單方法是:

var myDiv = document.getElementById("myDiv"); // Would find the DIV element by its ID, which in this case is 'myDiv'.

使用 getElementsByTagName 編輯

另一種在網頁上查找元素的方法是使用 getElementsByTagName(name) 方法。 它返回節點中所有 name 元素的數組。

假設,在一個頁面上,我們有:

<div id="myDiv">
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <h1>An HTML header</h1>
  <p>Paragraph 3</p>
</div>

使用 getElementsByTagName 方法,我們可以獲得 div 內所有 <p> 元素的數組:

var myDiv = document.getElementById("myDiv"); // get the div
var myParagraphs = myDiv.getElementsByTagName('P'); //get all paragraphs inside the div

// for example you can get the second paragraph (array indexing starts from 0)
var mySecondPar = myParagraphs[1]