Zac
Zac

Reputation: 12836

How do I select the anchor of a link wth pure javascript

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

Upvotes: 1

Views: 315

Answers (1)

lonesomeday
lonesomeday

Reputation: 237865

The only thing that you can select by there is the tag name (a). You can use the getElementsByTagName method for this:

var el = document.getElementsByTagName('a')[0];
el.className = 'foo';

Note that [0] selects the first element found by getElementsByTagName. Obviously this can return multiple elements.

If you want to search just within #foo, you could do this:

var foo = document.getElementById('foo'),
    el = foo.getElementsByTagName('a')[0];

This shows that you can use getElementsByTagName to 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:

var el = document.querySelectorAll('#foo a')[0];

Upvotes: 4

Related Questions