Last modified on 24 September 2014, at 10:06

JavaScript/Finding Elements

Previous: Introduction to the Document Object Model (DOM) Index Next: Adding Elements

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

Simple UseEdit

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 getElementsByTagNameEdit

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]
Previous: Introduction to the Document Object Model (DOM) Index Next: Adding Elements