Windows Dev Center

EN
Dieser Inhalt ist in Ihrer Sprache leider nicht verfügbar. Im Folgenden finden Sie die englische Version.

getElementsByTagName method

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.



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


Examples

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


<!DOCTYPE html>
<html>

<body>
  <p><strong>Click a list element:</strong></p>
  <ul id="outerUL">
    <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>
  <script>
    document.getElementById('outerUL').addEventListener('click', fnGetTags, false);

    function fnGetTags(evt) {
      var oWorkItem = evt.target;
      var aReturn = oWorkItem.parentElement.getElementsByTagName("li");

      console.log("Length: "
         + aReturn.length
         + "\nFirst Item: "
         + aReturn[0].childNodes[0].nodeValue);
    }
  </script>
</body>

</html>

See also

a
abbr
address
area
b
base
bdo
bgSound
blockQuote
body
br
button
caption
cite
code
col
colGroup
custom
dd
del
dfn
div
dl
document
dt
em
embed
fieldSet
form
frame
head
hn
hr
html
i
iframe
img
ins
kbd
label
legend
li
link
map
menu
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

 

 

Anzeigen:
© 2015 Microsoft