Getelement by class javascript

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.

Читайте также:  Notepad run in python

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.

Источник

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.

Источник

JavaScript Get Element By Class

In this tutorial, you will learn how Javascript get element by class of the element. You will look at different methods and will look at various examples for the same.

When you want to play with the DOM (Document Object Model) one of the most basic and important things that you would like to do is select the DOM elements.

There are many ways to select an element within the DOM like, getting element by id, getting element by class, getting element by tag name, etc. We will look here at how to get an element by class.

javascript get element by class

1. Using getElementsByClassName JavaScript

The getElementsByClassName method is used to get all the elements with the same class name in a document.

The method returns array-like objects of all the elements that have the same class name.

The method can be called in two ways:

  1. Calling on entire document — When the method called on document then it selects all the elements with the same class name in the document. Example — document.getElementsByClassName(‘class-name’)
  2. Calling on an element (parent) — When the method called on an element then it selects only the elements with the same class name in the element(parent). Example — parent.getElementsByClassName(‘class-name’)

Note : The method name is getElementsByClassName not getElementByClassName . Elements because there could be more than 1 element with a class name in a webpage.

1. Here is an example to get all elements with a class named ‘box’ in the document.

1. Method call on document

 

// calling method on document let elements = document.getElementsByClassName("box"); // outputs all elements with class "box" console.log(elements);

output 1

Here is an example to get all elements with a class named ‘box’ in a specific element.

2. Get elements only in the parent element by class

 

let parentElements = document.getElementById("id1"); // calling method on parent element let elements = document.getElementsByClassName("box"); // outputs elements with class "box" only in parent element console.log(elements);

output 2

Accessing element

The elements returned by the getElementsByClassName method can be accessed by its index values.

Each element has its index value in HTMLCollection starting from 0. So if you want to get the first element with some class use elements[0] .

Access element and add style to it

let parentElement = document.getElementById("id1"); function addStyle() < let elements = parentElement.getElementsByClassName("box"); for (let i = 0; i < elements.length; i++) < let myElement = elements[i]; // access element myElement.style.background = "lightgreen"; >>

Find element by class and add style

Get element with more than one class

If you want to select all the elements that have more than one mentioned class then pass the desired class names separated by spaces in the getElementsByClassName method.

Get elements with both classes ‘box’ and ‘bar’

Both box and bar class

Both box and bar class

Find element with classes box and bar

output 3

2. Using querySelector JavaScript

The querySelector method is a selector method in JavaScript that uses CSS selectors to find an element within the document.

It returns the first element within the document that matches the specified selector.

To get an element with a class pass the class name with a dot and it will return the first element that has the specified class.

Get the first element with the specified class

 

Findfirst element with class 'box' function addStyle()

output 4

3. Using querySelectorAll javascript

The querySelectorAll is also a method to selects elements on the basis of the CSS selector. The only difference between querySelector and querySelectorAll is that querySelectorAll selects all the elements matching the selector as an array-like object.

Get all elements with the specified class

 

Findfirst element with class 'box'

output 5

Conclusion

In this tutorial, you learned how to get an element by one or multiple classes in javascript by 3 different methods with their examples.

The methods discussed in this tutorial are querySelector , querySelectorAll and getElementsByClassName . The querySelector method is the most commonly used method to get an element by class name. The querySelectorAll method is used to get all the elements with the specified class name. The getElementsByClassName method is used to get all the elements with the specified class name.

Источник

Оцените статью