开发者

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 gra开发者_如何学Gob 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 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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜