How to access HTML element without ID?

For instance in the snippet below - how do I access the h1 element knowing the ID of parent element (header-inner div)?

<div id='header-inner'> 
   <div class='titlewrapper'> 
      <h1 class='title'> 
      Some text I want to change
      </h1> 
   </div> 
</div>

Thanks!


Solution 1:

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).

Solution 2:

If you were to use jQuery as mentioned by some posters, you can get access to the element very easily like so (though technically this would return a collection of matching elements if there were more than one H1 descendant):

var element = $('#header-inner h1');

Using a library like JQuery makes things like this trivial compared to the normal ways as mentioned in other posts. Then once you have a reference to it in a jQuery object, you have even more functions available to easily manipulate its content and appearance.

Solution 3:

If you are sure that there is only one H1 element in your div:

var parent = document.getElementById('header-inner');
var element = parent.GetElementsByTagName('h1')[0];

Going through descendants,as Shog9 showed, is a good way too.

Solution 4:

The simplest way of doing it with your current markup is:

document.getElementById('header-inner').getElementsByTagName('h1')[0].innerHTML = 'new text';

This assumes your H1 tag is always the first one within the 'header-inner' element.