< JavaScript

The most common method of detecting page elements in the DOM is by the document.getElementById(id) method.

Simple Use

Let's say, on a page, we have:

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

A simple way of finding this element in JavaScript would be:

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

Use of getElementsByTagName

Another way to find elements on a web page is by the getElementsByTagName(name) method. It returns an array of all name elements in the node.

Let's say, on a page, we have:

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

Using the getElementsByTagName method we can get an array of all <p> elements inside the div:

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]
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.