How to access HTML element without ID?

function findFirstDescendant(parent, tagname)
{
   parent = document.getElementById(parent);
   var descendants = parent.getElementsByTagName(tagname);
   if ( descendants.length )
      return descendants[0];
   return null;
}

var header = findFirstDescendant("header-inner", "h1");

Finds the element with the given ID, queries for descendants with a given tag name, returns the first one. You could also loop on descendants to filter by other criteria; if you start heading in that direction, i recommend you check out a pre-built library such as jQuery (will save you a good deal of time writing this stuff, it gets somewhat tricky).

Leave a Comment