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 :: javascript replace line breaks with br 
Javascript :: js get element window offset top 
Javascript :: javascript open link in new tab 
Javascript :: javascript convert string to float 
Javascript :: react native position absolute center 
Javascript :: js loop every second 
Javascript :: html include js file flask 
Javascript :: drupal 8 get page node 
Javascript :: trigger a click on page load jquery 
Javascript :: Error: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If 
Javascript :: hide header react navigation 
Javascript :: swiper js cdn 
Javascript :: How to get current URL with Javascript or React 
Javascript :: local storage check if key exists 
Javascript :: how to unmount bottom tab screens 
Javascript :: install node js in manjaro 
Javascript :: number with commas js 
Javascript :: reduce decimals to 4 digits javascript 
Javascript :: installing vuex 
Javascript :: how to know connected internet in js 
Javascript :: javascript appendchild image node 
Javascript :: how to refresh slick after tab function 
Javascript :: function to generate random color in javascript 
Javascript :: get text of selected option jquery 
Javascript :: yarn create react app 
Javascript :: navigate to url jquery 
Javascript :: syntax jquery 
Javascript :: javascript check format uuid 
Javascript :: call a function when page loads javascript 
Javascript :: react native rotate image 
ADD CONTENT
Topic
Content
Source link
Name
3+3 =