最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript getElementsByTagName - Stack Overflow

programmeradmin3浏览0评论

I'm trying to use the getElementsByTagName("a") method to get all the elements under a specific tag.

However, I don't want every anchor tag. How would I narrow it so I only select all the anchor tags under the the ul tag for "someListClass" name?

<ul class="someListClass"> <li><a href... /></li>... </ul>

I know in jQuery you can just select with $(".someListClass a").

How would I do it without using jQuery?

I'm trying to use the getElementsByTagName("a") method to get all the elements under a specific tag.

However, I don't want every anchor tag. How would I narrow it so I only select all the anchor tags under the the ul tag for "someListClass" name?

<ul class="someListClass"> <li><a href... /></li>... </ul>

I know in jQuery you can just select with $(".someListClass a").

How would I do it without using jQuery?

Share Improve this question asked Nov 3, 2009 at 11:55 LB.LB. 14.1k24 gold badges71 silver badges103 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 14

Give your ul an id and then use

<ul id="ulid" class="someListClass"> <li><a href... /></li>... </ul>

document.getElementById ( "ulid" ).getElementsByTagName ( "a" );

element.getElementsByTagName

elements = element.getElementsByTagName(tagName); 

elements is a live NodeList of found elements in the order they appear in the subtree.

element is the element from where the search should start. Note that only the descendants of this element are included in the search, but not the element itself.

tagName is the qualified name to look for. The special string "*" represents all elements. For compatibility with XHTML, lower-case should be used.

you can use

element.getElementsByTagName(tagName) 

where element is the UL item... so grab the UL item then search against that. something like:

<ul class="someListClass" id="myList"> <li><a href... /></li>... </ul>

var theList = document.getElementById('myList');
var listItems = theList.getElementsByTagName('li');

you want getElementsByClassName http://www.quirksmode.org/blog/archives/2008/05/getelementsbycl.html

  links = document.getElementsByClassName("someListClass")[0].getElementsByTagName("a")

Without a framework, I can think of no other way than going though each element manually and to iterate its parents. If one of them has the class "somelistClass", add it to the stack. Otherwise, not.

If you are looking for the children of a single element, phoenix's approach is the way to go.

发布评论

评论列表(0)

  1. 暂无评论