Finding Elements

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 uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.

JavaScript/Finding_elements
 



 

Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.


Manage research, learning and skills at defaultLogic. Create an account using LinkedIn or facebook to manage and organize your Digital Marketing and Technology knowledge. defaultLogic works like a shopping cart for information -- helping you to save, discuss and share.

Visit defaultLogic's partner sites below:
PopFlock.com : Music Genres | Musicians | Musical Instruments | Music Industry
NCR Works : Retail Banking | Restaurant Industry | Retail Industry | Hospitality Industry

  Contact Us