Html get element by class name

.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.

Источник

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.

Источник

Element: getElementsByClassName() method

The Element method getElementsByClassName() returns a live HTMLCollection which contains every descendant element which has the specified class name or names.

The method getElementsByClassName() on the Document interface works essentially the same way, except it acts on the entire document, starting at the document root.

Syntax

getElementsByClassName(names) 

Parameters

A string containing one or more class names to match on, separated by whitespace.

Return value

An HTMLCollection providing a live-updating list of every element which is a member of every class in names .

Usage notes

As always, the returned collection is live, meaning that it always reflects the current state of the DOM tree rooted at the element on which the function was called. As new elements that match names are added to the subtree, they immediately appear in the collection. Similarly, if an existing element that doesn’t match names has its set of classes adjusted so that it matches, it immediately appears in the collection.

The opposite is also true; as elements no longer match the set of names, they are immediately removed from the collection.

Note: In quirks mode, the class names are compared in a case-insensitive fashion. Otherwise, they’re case sensitive.

Examples

Matching a single class

To look for elements that include among their classes a single specified class, we just provide that class name when calling getElementsByClassName() :

.getElementsByClassName("test"); 

This example finds all elements that have a class of test , which are also a descendant of the element that has the id of main :

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

Matching multiple classes

To find elements whose class lists include both the red and test classes:

.getElementsByClassName("red test"); 

Examining the results

You can use either the item() method on the returned HTMLCollection or standard array syntax to examine individual elements in the collection. However, the following code will not work as one might expect because «matches» will change as soon as any «colorbox» class is removed.

const matches = element.getElementsByClassName("colorbox"); for (let i = 0; i  matches.length; i++)  matches[i].classList.remove("colorbox"); matches.item(i).classList.add("hueframe"); > 

Instead, use another method, such as:

const matches = element.getElementsByClassName("colorbox"); while (matches.length > 0)  matches.item(0).classList.add("hueframe"); matches[0].classList.remove("colorbox"); > 

This code finds descendant elements with the «colorbox» class, adds the class «hueframe» , by calling item(0) , then removes «colorbox» (using array notation). Another element (if any are left) will then become item(0) .

Filtering the results using array methods

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

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

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.

Источник

Читайте также:  clear
Оцените статью