Html get object by class

How to get HTML elements by class using JavaScript

The document.getElementsByClassName() method is used to get HTML elements by its class name. Suppose you have the following HTML tag:

You can grab both 

tags in the example above by using getElementsByClassName() method. The tags will be returned as an array-like object called HTMLCollection :

The getElementsByClassName() method always returns an array-like HTMLCollection even if you only have one element with that class name. You can also retrieve elements with more than one class names as follows:

   Keep in mind that even though you can access HTMLCollection object’s value like an array, the HTMLCollection object does not inherit methods from JavaScript Array prototype object.

This means JavaScript Array methods like forEach() , map() , or filter() can’t be called from an HTMLCollection object.

If you want to do something with all elements that match your selection, you need to use the document.querySelectorAll() method.

The querySelectorAll() method returns a NodeList object that implements the forEach() method.

And that will be all about the document.getElementsByClassName() method. Although there’s nothing wrong with using the method, selecting an element by using its id attribute is generally preferred over the class attribute because the id attribute is more precise and returns only a single element.

But of course, the choice is up to you as the developer to use which method fits your requirement best.

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

HTML DOM Document getElementsByClassName()

Get all elements with both the «example» and «color» classes:

Description

The getElementsByClassName() method returns a collection of elements with a specified class name(s).

The getElementsByClassName() method returns an HTMLCollection.

The getElementsByClassName() property is read-only.

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

Parameter Description
classname Required.
The class name of the elements.
Search for multiple class names separated by spaces like «test demo».

Return Value

Type Description
Object. An HTMLCollection object.
A collection of elements with the specified class name.
The elements are sorted as they appear in the document.

More Examples

Change the background color of all elements with >

const collection = document.getElementsByClassName(«example»);
for (let i = 0; i < collection.length; i++) collection[i].style.backgroundColor = "red";
>

Browser Support

document.getElementsByClassName() 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

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

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: getElementsByClassName() method

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s).

When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class name(s).

Warning: This is a live HTMLCollection . Changes in the DOM will reflect in the array as the changes occur. If an element selected by this array no longer qualifies for the selector, it will automatically be removed. Be aware of this for iteration purposes.

Syntax

getElementsByClassName(names) 

Parameters

A string representing the class name(s) to match; multiple class names are separated by whitespace.

Return value

A live HTMLCollection of found elements.

Examples

Get all elements that have a class of ‘test’:

.getElementsByClassName("test"); 

Get all elements that have both the ‘red’ and ‘test’ classes:

.getElementsByClassName("red test"); 

Get all elements that have a class of ‘test’, inside of an element that has the ID of ‘main’:

.getElementById("main").getElementsByClassName("test"); 

Get the first element with a class of ‘test’, or undefined if there is no matching element:

.getElementsByClassName("test")[0]; 

We can also use methods of Array.prototype on any HTMLCollection by passing the HTMLCollection as the method’s this value. Here we’ll find all div elements that have a class of ‘test’:

const testElements = document.getElementsByClassName("test"); const testDivs = Array.prototype.filter.call( testElements, (testElement) => testElement.nodeName === "DIV", ); 

Get the first element whose class is ‘test’

This is the most commonly used method of operation.

html lang="en"> body> div id="parent-id"> p>hello world 1p> p class="test">hello world 2p> p>hello world 3p> p>hello world 4p> div> script> const parentDOM = document.getElementById("parent-id"); const test = parentDOM.getElementsByClassName("test"); // a list of matching elements, *not* the element itself console.log(test); // HTMLCollection[1] const testTarget = parentDOM.getElementsByClassName("test")[0]; // the first element, as we wanted console.log(testTarget); // 

hello world 2

script> body> html>

Multiple Classes Example

document.getElementsByClassName works very similarly to document.querySelector and document.querySelectorAll . Only elements with ALL of the classNames specified are selected.

HTML

span class="orange fruit">Orange Fruitspan> span class="orange juice">Orange Juicespan> span class="apple juice">Apple Juicespan> span class="foo bar">Something Randomspan> textarea id="resultArea" style="width:98%;height:7em">textarea> 

JavaScript

// getElementsByClassName only selects elements that have both given classes const allOrangeJuiceByClass = document.getElementsByClassName("orange juice"); let result = "document.getElementsByClassName('orange juice')"; for (let i = 0; i  allOrangeJuiceByClass.length; i++)  result += `\n $allOrangeJuiceByClass[i].textContent>`; > // querySelector only selects full complete matches const allOrangeJuiceQuery = document.querySelectorAll(".orange.juice"); result += "\n\ndocument.querySelectorAll('.orange.juice')"; for (let i = 0; i  allOrangeJuiceQuery.length; i++)  result += `\n $allOrangeJuiceQuery[i].textContent>`; > document.getElementById("resultArea").value = result; 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

.get Elements By Class Name ( )

Метод определён для объекта document и любого HTML-элемента ( Element ) страницы. Позволяет найти все элементы с заданным классом или классами среди дочерних.

Метод принимает один параметр — название класса или список классов в виде строки. Если передаёшь список классов, то раздели их названия пробелами class1 class2 . Элемент подходит, если у него есть все классы из перечисленных.

Возвращает похожую на массив HTML Collection с найденными элементами. Если элементов не нашлось, то коллекция будет пустая, то есть с размером 0.

Пример

Скопировать ссылку «Пример» Скопировано

     

Привет, незнакомец!

Div с классом paragraph и subtitle

Параграф с классом paragraph

const paragraphs = document.getElementsByClassName('paragraph') console.log(paragraphs.length) // напечатает 2 const divEl = document.getElementById('title') // ищем параграфы внутри div: const paragraphsFromDiv = divEl.getElementsByClassName('paragraph') console.log(paragraphsFromDiv.length) // напечатает 1, так как внутри div только один элемент с классом paragraph const subtitleParagraphs = document.getElementsByClassName( 'paragraph subtitle' ) console.log(subtitleParagraphs.length) // напечатает 1, так как на странице только один элемент, // у которого есть и класс paragraph, и класс subtitle // ищем несуществующий элемент const spanFromBody = document.getElementsByClassName('hello') console.log(spanFromBody.length) // напечатает 0
html> head>head> body> div id="title"> h1>Привет, незнакомец!h1> div class="paragraph subtitle">Div с классом paragraph и subtitlediv> div> p class="paragraph">Параграф с классом paragraphp> script> const paragraphs = document.getElementsByClassName('paragraph') console.log(paragraphs.length) // напечатает 2 const divEl = document.getElementById('title') // ищем параграфы внутри div: const paragraphsFromDiv = divEl.getElementsByClassName('paragraph') console.log(paragraphsFromDiv.length) // напечатает 1, так как внутри div только один элемент с классом paragraph const subtitleParagraphs = document.getElementsByClassName( 'paragraph subtitle' ) console.log(subtitleParagraphs.length) // напечатает 1, так как на странице только один элемент, // у которого есть и класс paragraph, и класс subtitle // ищем несуществующий элемент const spanFromBody = document.getElementsByClassName('hello') console.log(spanFromBody.length) // напечатает 0 script> body> html>

Как понять

Скопировать ссылку «Как понять» Скопировано

Метод работает с DOM, который связан с HTML-разметкой. Каждый HTML-элемент имеет родительские и дочерние элементы:

  • Родительские элементы — это элементы, внутри которых находится элемент. В примере выше у элемента есть два родительских элемента — и .
  • Дочерние элементы — это элементы, которые содержит текущий элемент. Они могут быть, а могут не быть. Например, для тега все элементы страницы дочерние. У дочерний элемент — текст внутри тега.

Если работаешь с корнем страницы, объектом document , то поиск идёт по всем элементам страницы (т.е. от ), если от конкретного элемента, то поиск идёт только по всем дочерним.

Так как мы заранее не знаем, сколько элементов с искомым тегом найдётся, то метод возвращает коллекцию элементов.

Каждый элемент HTML может иметь класс или несколько классов. Когда пользуетесь get Elements By Class Name ( ) , поиск идёт только по классам (атрибут class ). Названия тегов и все остальные атрибуты игнорируются.

На практике

Скопировать ссылку «На практике» Скопировано

Николай Лопин советует

Скопировать ссылку «Николай Лопин советует» Скопировано

🛠 Метод возвращает живую коллекцию. Это означает, что коллекция будет автоматически обновляться, если на странице появятся подходящие элементы. Если не очень понятно, как это работает, то посмотрите пример в статье по методу get Elements By Tag Name ( ) .

🛠 Нужно быть осторожным, когда пишете циклы над HTML Collection . Так как коллекция живая, то цикл может стать бесконечным в тех случаях, когда на страницу добавляются и удаляются подходящие под поиск элементы.

🛠 Скрипты, которые работают с HTML видят только ту разметку, которую уже распарсил браузер. Браузер парсит HTML сверху вниз. Если ваш скрипт находится вверху страницы, то он не найдёт элементы ниже в странице — браузер их ещё не увидел и ничего о них не знает. Поэтому скрипты либо подключают в конце страницы, либо подписываются на событие DOM Content​ Loaded , которое сигнализирует о том, что браузер распарсил весь HTML.

Источник

Читайте также:  Адаптивная галерея html css
Оцените статью