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 loop through object array 
Javascript :: javascript filter strings for partial matches 
Javascript :: discord.js leave guild 
Javascript :: javascript int with commas 
Javascript :: retrieve object array value based on key 
Javascript :: reactjs add border to the table row 
Javascript :: axios get error message 
Javascript :: tab navigation react-native without title 
Javascript :: orthographic camera three js 
Javascript :: onload set scroll on top of page jquery 
Javascript :: datatables ajax reload 
Javascript :: javascript get line number of error 
Javascript :: mysql json change key 
Javascript :: chrome extension communication between popup and content script 
Javascript :: cheerio load 
Javascript :: json server npm 
Javascript :: nuxt redirect traffic from http to https 
Javascript :: body on click function 
Javascript :: how to run method in method vue js on load 
Javascript :: require() of ES modules is not supported when importing node-fetch 
Javascript :: ajax data and image upload laravel 
Javascript :: why use currying 
Javascript :: js bmi calculator 
Javascript :: javascript order by string array 
Javascript :: make link disabled in angular 
Javascript :: canada postal code regex 
Javascript :: navigate to another page in javascript 
Javascript :: How to Get the First n Characters of a String in javascript 
Javascript :: linking in react native 
Javascript :: datatable after loading function 
ADD CONTENT
Topic
Content
Source link
Name
9+5 =