Manohar Kulanthai vel Manohar Kulanthai vel - 1 month ago 14
Javascript Question

How to use document.getElementByName and getElementByTag?

document.getElementById('frmMain').elements


can i use like this

document.getElementByName('frmMain').elements


or

document.getElementBytag('table').elements`

Answer
document.getElementById('frmMain').elements 
  • assumes the form has an ID, will however also work with name in IE, but please add ID if you want to use getElementById

document.getElementsByName('frmMain')[0].elements 
  • will get the elements of the first object named frmMain on the page - notice the plural getElements - it will return a collection.

document.getElementsByTagName('form')[0].elements
  • will get the elements of the first form on the page based on the tag - again notice the plural getElements

A great alternative is the newer

document.querySelector("form").elements 
  • will get the elements of the first form on the page. The "form" is a valid CSS selector