退货 (Returns)
例 (Example)
var paragraphs = document.getElementByTagName('p');
The example above gets a reference to the collection of p
elements within the current document, and saves it to the variable paragraphs. The returned collection is live, which means that changes to the HTML it represents are immediately reflected in the collection, without having to retrieve it again.
上面的示例获取了当前文档中p
元素的集合的引用,并将其保存到变量parass中 。 返回的集合是live ,这意味着对它表示HTML的更改将立即反映在该集合中,而无需再次检索它。
This method can also be used contextually, to get a reference to the elements that are inside a specific element, for example:
也可以在上下文中使用此方法,以获取对特定元素内部元素的引用,例如:
var items = list.getElementByTagName('li');
So if the list in that example were a ul
element, the items variable would refer to a collection of all the li
elements that are inside that list.
因此,如果该示例中的列表是ul
元素,则items变量将引用该列表内所有li
元素的集合。
The elements are retrieved in the linear order in which they appear in the document, ie. they correspond to a flattened view of the DOM. So if, in the previous example, the list corresponded with this HTML:
元素以它们在文档中出现的线性顺序检索,即。 它们对应于DOM的扁平视图。 因此,在上一个示例中,如果列表与此HTML相对应:
<ul>
<li>Cheeses
<ul>
<li>Edam</li>
<li>Gouda</li>
<li>Cheddar</li>
</ul>
</li>
<li>Hams
<ul>
<li>Prosciutto</li>
<li>Parma</li>
<li>Salami</li>
</ul>
</li>
</ul>
The returned collection would be in the following order:
返回的集合将按以下顺序:
[0]
Cheeses[0]
奶酪[1]
Edam[1]
伊丹[2]
Gouda[2]
高达[3]
Cheddar[3]
切达干酪[4]
Hams[4]
火腿[5]
Prosciutto[5]
意大利熏火腿[6]
Parma[6]
帕尔马[7]
Salami[7]
萨拉米香肠
争论 (Arguments)
name (DOMString)
required The tagName
of the elements to match. The value * matches all elements.
名称 ( DOMString )
tagName
需要匹配的元素的tagName
。 值*匹配所有元素。
描述 (Description)
Get an ordered list of all elements with a given tag name, that are descendents of this document or element, in the linear order in which they appear in the DOM tree.
获取具有给定标签名称的所有元素的有序列表,这些元素是此文档或元素的后代,以它们在DOM树中出现的线性顺序排列。
The returned collection is a NodeList
— an ordered collection of nodes, indexed numerically starting from zero. If there are no matching elements then it’s a collection with zero members.
返回的集合是NodeList
节点的有序集合,从零开始以数字方式索引。 如果没有匹配的元素,则它是一个零成员的集合。
集合不是数组 (A collection is not an array)
Even though a collection looks like an array, it isn’t an array — although you can iterate through it and refer to its members like an array, you can’t use Array methods like push or pop on it.
即使一个集合看起来像一个数组,它也不是一个数组-尽管您可以遍历它并像数组一样引用它的成员,但是不能在其上使用push或pop这样的Array方法。
返回值 (Return value)
A NodeList containing all the matched elements ; if no elements are found this will be a list with zero members.
一个包含所有匹配元素的NodeList; 如果未找到任何元素,则该列表将为零成员。
翻译自: https://www.sitepoint.com/getelementsbytagname-w3c-dom-core-method/