- HTML DOM Document getElementsByTagName()
- Description
- Note
- HTMLCollection
- See Also:
- Syntax
- Parameters
- Return Value
- More Examples
- Related Pages
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Document: getElementsByTagName() method
- Syntax
- Parameters
- Return value
- Examples
- Notes
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- Element.getElementsByTagName()
- Синтаксис
- Пример
- Спецификации
- Совместимость браузеров
- Found a content problem with this page?
- Javascript getelementsbytagname type text
- # Get all Elements by Type using JavaScript
- # Get all elements by type attribute
- # Select all elements that have a type attribute set to text
- # Get all input elements on the page
- # Iterating over a collection of elements
- # Get all elements by Type using getElementsByTagName
- # Iterating over an HTMLCollection
- # Additional Resources
HTML DOM Document getElementsByTagName()
Change the inner HTML of the first
element in the document:
Description
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.
Note
getElementsByTagName(«*») returns all elements in the document.
HTMLCollection
An HTMLCollection is an array-like collection (list) of HTML elements.
The elements in a collection can be accessed by index (starts at 0).
The length Property returns the number of elements in the collection.
See Also:
Syntax
Parameters
Return Value
Type | Description |
Object | An HTMLCollection object. A collection of elements with a specified tag name. The elements are sorted as they appear in the document. |
More Examples
Change the background color of all
elements:
const collection = document.getElementsByTagName(«P»);
for (let i = 0; i < collection.length; i++) collection[i].style.backgroundColor = "red";
>
Related Pages
Browser Support
document.getElementsByTagName() is a DOM Level 1 (1998) feature.
It is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Document: getElementsByTagName() method
The getElementsByTagName method of Document interface returns an HTMLCollection of elements with the given tag name.
The complete document is searched, including the root node. The returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with the DOM tree without having to call document.getElementsByTagName() again.
Syntax
Parameters
A string representing the name of the elements. The special string * represents all elements.
Return value
A live HTMLCollection of found elements in the order they appear in the tree.
Note: The latest W3C specification says returned value is an HTMLCollection ; however, this method returns a NodeList in WebKit browsers. See Firefox bug 14869 for details.
Examples
In the following example, getElementsByTagName() starts from a particular parent element and searches top-down recursively through the DOM from that parent element, building a collection of all descendant elements which match the tag name parameter. This demonstrates both document.getElementsByTagName() and the functionally identical Element.getElementsByTagName() , which starts the search at a specific element within the DOM tree.
Clicking the buttons uses getElementsByTagName() to count the descendant paragraph elements of a particular parent (either the document itself or one of two nested elements).
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>getElementsByTagName exampletitle> script> function getAllParaElems() const allParas = document.getElementsByTagName("p"); const num = allParas.length; alert(`There are $num> paragraph in this document`); > function div1ParaElems() const div1 = document.getElementById("div1"); const div1Paras = div1.getElementsByTagName("p"); const num = div1Paras.length; alert(`There are $num> paragraph in #div1`); > function div2ParaElems() const div2 = document.getElementById("div2"); const div2Paras = div2.getElementsByTagName("p"); const num = div2Paras.length; alert(`There are $num> paragraph in #div2`); > script> head> body style="border: solid green 3px"> p>Some outer textp> p>Some outer textp> div id="div1" style="border: solid blue 3px"> p>Some div1 textp> p>Some div1 textp> p>Some div1 textp> div id="div2" style="border: solid red 3px"> p>Some div2 textp> p>Some div2 textp> div> div> p>Some outer textp> p>Some outer textp> button onclick="getAllParaElems();"> Show all p elements in document button> br /> button onclick="div1ParaElems();"> Show all p elements in div1 element button> br /> button onclick="div2ParaElems();"> Show all p elements in div2 element button> body> html>
Notes
When called on an HTML document, getElementsByTagName() lower-cases its argument before proceeding. This is undesirable when trying to match camelCase SVG elements in a subtree in an HTML document. document.getElementsByTagNameNS() is useful in that case. See also Webkit bug 499656.
document.getElementsByTagName() is similar to Element.getElementsByTagName() , except that its search encompasses the whole document.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- Element.getElementsByTagName()
- document.getElementById() to return a reference to an element by its id
- document.getElementsByName() to return a reference to an element by its name
- document.querySelector() for powerful selectors via queries like ‘div.myclass’
Found a content problem with this page?
This page was last modified on Apr 7, 2023 by MDN contributors.
Your blueprint for a better internet.
Element.getElementsByTagName()
Element.getElementsByTagName() метод возвращает живую коллекцию элементов HTMLCollection , учитывая имя тэга. Поиск осуществляется в поддереве указанного элемента, в результат поиска не попадает сам элемент, в поддереве которого осуществлялся поиск. Возвращает живой список, который автоматически обновляется при изменении DOM. Поэтому не нужно вызывать метод Element.getElementsByTagName() несколько раз с одними и теми же аргументами, содержимое списка обновляется автоматически.
При вызове на HTML-элементе в HTML-документе метод getElementsByTagName переводит аргумент по которому осуществляется поиск (имя тега) в нижний регистр до того как начать поиск. Это нежелательно, когда необходимо использовать метод для поиска SVG элементов, где в наименовании тега может использоваться верблюжья (camel-cased) нотация. В этом случае правильно использовать метод Element.getElementsByTagNameNS() (en-US).
Element.getElementsByTagName похож на Document.getElementsByTagName() , за исключением того, что поиск осуществляется среди потомков конкретного элемента, а не во всём HTML-документе.
Синтаксис
elements = element.getElementsByTagName(tagName)
- elements это живая коллекция HTMLCollection найденных элементов в том порядке, в котором они были найдены в дереве. Если не найдено ни одного элемента, удовлетворяющего условиям поиска, то коллекция будет пустой.
- element это элемент в котором будет осуществляться поиск. Обратите внимание, что поиск будет осуществляться только в потомках этого элемента. Сам элемент не будет включён в результат поиска.
- tagName определяет имя тега для поиска. Если значением tagName будет «*», то в результате будут получены все потомки элемента по которому осуществляется поиск . Для совместимости с XHTML следует использовать нижний регистр в имени тега.
Пример
// check the alignment on a number of cells in a table. var table = document.getElementById("forecast-table"); var cells = table.getElementsByTagName("td"); for (var i = 0; i cells.length; i++) var status = cells[i].getAttribute("data-status"); if ( status == "open" ) // grab the data > >
Спецификации
Совместимость браузеров
BCD tables only load in the browser
Found a content problem with this page?
This page was last modified on 7 нояб. 2022 г. by MDN contributors.
Your blueprint for a better internet.
Javascript getelementsbytagname type text
Last updated: Jan 12, 2023
Reading time · 2 min
# Get all Elements by Type using JavaScript
Use the querySelectorAll() method to get all elements by type.
The method returns a NodeList containing the elements that match the provided selector.
Here is the HTML for the examples.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> input type="text" id="first_name" /> input type="number" id="age" /> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!// ✅ Get all input elements with type = "text" const elements1 = document.querySelectorAll('input[type="text"]'); console.log(elements1); // 👉️ [input#first_name] // ------------------------------------------------------- // ✅ Get all input elements const elements2 = document.querySelectorAll('input'); console.log(elements2); // 👉️ [input#first_name, input#age] // ------------------------------------------------------- // ✅ Get all input elements const elements3 = document.getElementsByTagName('input'); console.log(elements3); // 👉️ [input#first_name, input#age]
# Get all elements by type attribute
In the first example, we used the document.querySelectorAll method to get all input elements that have a type attribute with a value of text .
Copied!const elements1 = document.querySelectorAll('input[type="text"]'); console.log(elements1); // 👉️ [input#first_name] console.log(elements[0]); // 👉️ input#first_name
If you want to get a specific element, you can access the NodeList at an index.
JavaScript indexes are zero-based, so the first element in the NodeList has an index of 0 .
# Select all elements that have a type attribute set to text
You can adjust the selector as needed, e.g. the following example selects any type of element with a type attribute set to a value of text (not just input elements).
Copied!const elements = document.querySelectorAll('[type="text"]'); console.log(elements); // 👉️ NodeList [input#first_name]
# Get all input elements on the page
In the second example, we used the querySelectorAll method to get a NodeList of all of the input tags.
Copied!const elements = document.querySelectorAll('input'); console.log(elements); // 👉️ NodeList(2) [input#first_name, input#age]
# Iterating over a collection of elements
If you need to iterate over the collection, use the forEach() method.
Copied!const elements = document.querySelectorAll('input'); console.log(elements); // 👉️ [input#first_name, input#age] elements.forEach(element => console.log(element); >);
# Get all elements by Type using getElementsByTagName
The third example uses the document.getElementsByTagName method to select all input tags.
Copied!const elements = document.getElementsByTagName('input'); console.log(elements); // 👉️ [input#first_name, input#age]
This serves as an alternative to the querySelectorAll method and you might see the getElementsByTagName method used in older code bases.
# Iterating over an HTMLCollection
The method returns an HTMLCollection , which you have to convert to an array if you need to use methods like forEach() .
Copied!const elements = Array.from(document.getElementsByTagName('input')); console.log(elements); // 👉️ [input#first_name, input#age] elements.forEach(element => console.log(element); >);
By converting the HTMLCollection to an array, we are able to use any of the array-supported methods.
You can also use a for. of loop to iterate over the collection.
Copied!const elements = Array.from(document.getElementsByTagName('input')); console.log(elements); // 👉️ [input#first_name, input#age] for (const element of elements) console.log(element); >
If you need to get a specific element, access the array at an index.
Copied!const elements = Array.from(document.getElementsByTagName('input')); console.log(elements); // 👉️ [input#first_name, input#age] console.log(elements[0]); // inptu#first-name console.log(elements[elements.length - 1]); // input#age
The first element in the array has an index of 0 and the last element has an index of array.length — 1 .
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.