0

I'm trying to get all of the following tags inside the body (INPUT, A, and BUTTON) is there a way to do that without having to loop through all the tags inside the body using javascript

var allInputTags = document.body.getElementsByTagName('*');

I was thinking to do something like

var inputtags = document.body.getElementsByTagName('INPUT');
var atags = document.body.getElementsByTagName('A');
var buttontags = document.body.getElementsByTagName('BUTTON');

var allTags = inputtags + atags + buttontags; 

but I think in that way I will not get the elements in the order they appear in the Body.

Kaiusee
  • 1,253
  • 1
  • 14
  • 28

2 Answers2

3

If the browser supports querySelectorAll [MDN], you can do :

var allTags = document.querySelectorAll('input, a, button');

The elements are returned in document order. See caniuse.com for a list of browsers that support querySelectorAll.

In all other browsers, you have to use getElementsByTagName but then I think it's going to be very difficult to get the element in order.

You can also consider to use a selector engine, such as Sizzle (the engine used by jQuery). Or if you plan to do complex DOM operations, jQuery itself.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • `querySelectorAll` has excellent support as far as desktop browsers are concerned. – Ana Oct 14 '12 at 18:03
1

You can use Array.concat

var allTags = inputtags.concat(atags, buttontags); 
Anoop
  • 23,044
  • 10
  • 62
  • 76