Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

javascript loop through class elements

var els = document.getElementsByClassName("myClass");
for(var i = 0; i < els.length; i++)
{
  console.log(els[i]);
}
Comment

javascript loop through class elements

// get elements based on their class name/s
const elements = Array.from(document.getElementsByClassName("css_class_name"));
// using for loop
for (let i = 0; i < elements.length; i++) {
	console.log(elements[i]);
}
// using for of loop
for (const element of elements) {
	console.log(element);
}
/*
using for in loop (Note: this will iterate through keys
in an object, otherwise you wouldn't need to convert the
HTMLCollection returned by
document.getElementsByClassName into an Array)
*/
for (const i in elements) {
	console.log(elements[i]);
}
/*
Note: these all achieve the same thing, but are slightly
different. The basic for loop is actually faster than
the for of and for in loops (by a miniscule, unnoticable
amount). Generally, you want to use whichever version
is most readable for you personally. In this case, the
for of loop is probably the most readable, followed by
the for loop. It is incredibly unlikely you would ever
need use a for in loop in a scenario like this.
*/
Comment

PREVIOUS NEXT
Code Example
Javascript :: get platform node 
Javascript :: react router Link does work 
Javascript :: check when keyup an input from a specific form jquery 
Javascript :: how to capitalize string in javascript 
Javascript :: split words in javascript 
Javascript :: vue htmlWebpackPlugin.options.title 
Javascript :: get uploaded file name in js 
Javascript :: javascript loop through object 
Javascript :: convert json string to javascript object 
Javascript :: select2 preselect option 
Javascript :: set a timer for 10 minutes 
Javascript :: random light color js 
Javascript :: js exec vs match 
Javascript :: Get the value of selected radio button 
Javascript :: remove whitespace javascript 
Javascript :: javascript remove all child elements 
Javascript :: hashtag strategy angular 
Javascript :: clear location state react 
Javascript :: handling scrolling on react router transitions 
Javascript :: Get child node index 
Javascript :: change object key name javascript es6 
Javascript :: js add css class to element 
Javascript :: get value of checked radio button jquery 
Javascript :: check type javascript 
Javascript :: remove character at index 
Javascript :: javascript check date greater than today 
Javascript :: how to access child img src in jquery 
Javascript :: redirect page using javascript 
Javascript :: select a random element from from items array 
Javascript :: react-native resource android:attr/lStar not found in Android 
ADD CONTENT
Topic
Content
Source link
Name
7+6 =