JavaScript/Finding Elements
From Wikibooks, open books for an open world
The most common method of detecting page elements in the DOM is by the document.getElementById(id) method.
[edit] 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'.
[edit] 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]