getElementsByTagName method

1 out of 2 rated this helpful - Rate this topic

Retrieves a collection of objects based on the specified element name.

Document Object Model (DOM) Level 2 HTML Specification, Section 1.6.5

Syntax

object.getElementsByTagName(v)

Parameters

v [in]

Type: String

String that specifies the name of an element.

Return value

Type: Element

Returns a collection of objects with the specified element name.

Standards information

Remarks

The getElementsByTagName method is equivalent to using the tags method on the all collection. For example, the following code shows how to retrieve a collection of div elements from the body element, first using the Dynamic HTML (DHTML) Object Model and then the Document Object Model (DOM).

  • Using the DHTML Object Model:
    
    var aDivs = document.body.all.tags("div");
    
    
  • Using the DOM:
    
    var aDivs = document.body.getElementsByTagName("div");
    
    

When you use the getElementsByTagName method, all child and nested child elements with the specified tag name are returned. For example, all of the span elements in the following example would be returned by the getElementsByTagName method.



<script type="text/javascript">
var aSpans = oDiv.getElementsByTagName("span");
</script>
<div id="oDiv">
    <span>Immediate Child
        <div>
            <span>Child of Child div</span>
        </div>
    </span>
</div>


Examples

The following example uses the getElementsByTagName method to return the children of a ul element based on the selected li element.


 
<script type="text/javascript">
  function fnGetTags() {
    var oWorkItem = event.srcElement;
    var aReturn = oWorkItem.parentElement.getElementsByTagName("li");
    console.log("Length: "
       + aReturn.length
       + "\nFirst Item: "
       + aReturn[0].childNodes[0].nodeValue);
  }
</script>
<ul onclick="fnGetTags()">
<li>Item 1
   <ul>
      <li>Sub Item 1.1
      <OL>
         <LI>Super Sub Item 1.1</li>
         <LI>Super Sub Item 1.2</li>
      </OL>
      </li>
      <li>Sub Item 1.2</li>
      <li>Sub Item 1.3</li>
   </ul>		
</li> 
<li>Item 2
   <ul>
      <li>Sub Item 2.1</li>
      <li>Sub Item 2.3</li>
   </ul>
</li>
<LI>Item 3</LI>
</ul>
 


See also

a
abbr
address
area
b
base
bdo
blockQuote
body
br
button
caption
cite
code
col
colGroup
custom
dd
del
div
dl
document
dt
em
embed
fieldSet
form
head
hn
hr
html
i
iframe
img
ins
kbd
label
legend
li
link
map
ol
p
pre
q
s
samp
script
select
small
span
strong
sub
sup
table
tBody
td
textArea
tFoot
th
tHead
title
tr
u
ul
var
About the W3C Document Object Model

 

 

Build date: 11/28/2012

Did you find this helpful?
(1500 characters remaining)
© 2013 Microsoft. All rights reserved.