So if I have a DOM like this :
<div id="foo">
<ul><li><a href="#"></a></li></ul>
</div>
I understand to grab the div I would do
document.getElementById("foo");
but how could I grab the a ? I am trying to add a class to the a href.
ME = spoiled by jQuery
The only thing that you can select by there is the tag name (
a). You can use thegetElementsByTagNamemethod for this:Note that
[0]selects the first element found bygetElementsByTagName. Obviously this can return multiple elements.If you want to search just within
#foo, you could do this:This shows that you can use
getElementsByTagNameto search within the context of another element.One final method — that isn’t supported in all browsers (i.e. Firefox 3 or before, IE 7 or before) — is
querySelectorAll, which allows you to use CSS selectors much as you would in jQuery. For instance: