Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript getElementsByTagName

Tags:

javascript

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?

like image 971
LB. Avatar asked Nov 03 '09 11:11

LB.


People also ask

What is getElementsByTagName in JavaScript?

The getElementsByTagName() method returns a collection of all elements with a specified tag name. The getElementsByTagName() method returns an HTMLCollection. The getElementsByTagName() property is read-only.

What is the difference between GetElementByID and getElementsByTagName?

The difference is that GetElementByID() will retrieve a single element object based on the unique id specified, whereas GetElementsByTagName() will retrieve an array of all element objects with the specified tag name. Then you can obtain the value using GetElementById from your C++ code.

Why getElementsByTagName is not working?

The "getElementsByTagName is not a function" error occurs for multiple reasons: calling the getElementsByTagName() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. misspelling getElementsByTagName (it's case sensitive).

What does getElementsByTagName return?

getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name. All descendants of the specified element are searched, but not the element itself. The returned list is live, which means it updates itself with the DOM tree automatically.


1 Answers

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.

like image 181
rahul Avatar answered Oct 11 '22 01:10

rahul