JavaScript/Finding elements

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>

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: Runtime document manipulation Index Next: Adding elements