Javascript get all classes element

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.

Источник

How to get all css classes of an element in Javascript?

In JavaScript, it’s common to want to get all the CSS classes applied to an HTML element, in order to manipulate them dynamically. There are a few different methods to achieve this, which vary in their syntax and the information they return. It’s important to note that not all of these methods are universally supported across all browsers, so it’s important to choose the right method for your specific needs and target audience.

Method 1: Element.classList

To get all CSS classes of an HTML element in JavaScript, you can use the Element.classList property. This property returns a collection of the class attributes of the element. Here is an example code that demonstrates how to use Element.classList to get all CSS classes of an element:

const element = document.getElementById('myElement'); // get the element by its ID const classes = element.classList; // get the classList property of the element // loop through the classes and log them to the console for (let i = 0; i  classes.length; i++)  console.log(classes[i]); >

This code gets an HTML element with the ID myElement and stores it in the element variable. Then, it gets the classList property of the element and stores it in the classes variable. Finally, it loops through the classes collection and logs each class name to the console.

You can also use the Array.from() method to convert the classList collection into an array:

const element = document.getElementById('myElement'); // get the element by its ID const classes = Array.from(element.classList); // convert the classList collection into an array // loop through the classes and log them to the console for (let i = 0; i  classes.length; i++)  console.log(classes[i]); >

This code does the same thing as the previous example, but it converts the classList collection into an array using the Array.from() method. This makes it easier to work with the classes as an array.

You can also use the forEach() method to loop through the classes:

const element = document.getElementById('myElement'); // get the element by its ID const classes = element.classList; // get the classList property of the element // loop through the classes and log them to the console classes.forEach(className =>  console.log(className); >);

This code does the same thing as the previous examples, but it uses the forEach() method to loop through the classes. This is a more concise way to loop through an array or collection in JavaScript.

In summary, to get all CSS classes of an HTML element in JavaScript, you can use the Element.classList property. You can loop through the classes using a for loop, convert the collection into an array using the Array.from() method, or use the forEach() method to loop through the classes.

Method 2: Element.className

To get all CSS classes of an element in Javascript using Element.className , you can follow these steps:

  1. Get the element you want to retrieve the classes from. You can use document.querySelector() to select the element by its tag, class, or id.
const element = document.querySelector('.my-element');
const classes = element.className;
  1. If you want to access each class separately, you can split the string into an array using the String.split() method.
const classArray = classes.split(' ');
classArray.forEach((className) =>  console.log(className); >);
const element = document.querySelector('.my-element'); const classes = element.className; const classArray = classes.split(' '); classArray.forEach((className) =>  console.log(className); >);

This code will retrieve all the CSS classes of the element with the class «my-element» and log them to the console.

Method 3: getAttribute(«class»)

To get all CSS classes of an element using getAttribute(«class») in JavaScript, you can follow these steps:

  1. First, select the element whose CSS classes you want to retrieve. You can use any selector method like querySelector() or getElementById() .
const element = document.querySelector('.my-element');
const classes = element.getAttribute('class');
  1. The getAttribute() method will return a string containing all the CSS classes of the element separated by a space. You can split this string into an array of individual class names using the split() method.
const classList = classes.split(' ');
  1. The classList array will contain all the CSS classes of the selected element. You can then loop through this array to perform any desired operations.
classList.forEach(className =>  console.log(className); >);

Here’s the complete code example:

const element = document.querySelector('.my-element'); const classes = element.getAttribute('class'); const classList = classes.split(' '); classList.forEach(className =>  console.log(className); >);

This code will log all the CSS classes of the selected element to the console. Note that this method will only work if the class attribute of the element contains valid CSS class names separated by spaces.

Источник

Читайте также:  Java oracle driver jar
Оцените статью