Jump to content

How can I convert this for loop to a forEach loop?


kayut

Recommended Posts

Hey,

I have two divs with class demo and want to change their border.
I can do this as follow:

<div class="demo">first div</div>
<div class="demo">second div</div>
	let myClass = document.getElementsByClassName('demo');
console.log(myClass); // is an array
 for (i = 0; i < myClass.length; i++) {
   myClass[i].style.border = '1px solid red';
 }


I know that myClass is an array. So, I should be able to iterate through it with forEach method, isn't it?
But how?

Thanks

Link to comment
Share on other sites

Hi, Kayut!

The w3school Team appears to be on vacation.

Have you tried jQuery?  It is reformatted Javascript.  So you can easily intermix the two.  Below is all you need.

<script> $(".demo").css("border","1px solid red:); </script>

Roddy

Link to comment
Share on other sites

@iwato,

I think you didn't read my question properly. Your answer has nothing to do with my question.

First, this is a forum for JavaScript and not for jQuery.

Second, my question is about forEach and your solution has nothing to do with forEach!

Edited by kayut
Link to comment
Share on other sites

That's not actually an array, it's an HTMLCollection. It behaves a bit like an array, but does not have any of the array-specific methods like .slice() or .forEach(). If you use document.querySelectorAll() it will give you a NodeList object which does have a forEach() method.

jQuery is a program built with Javascript, it is more inefficient and memory-intensive than regular Javascript by a couple of orders of magnitude.

Link to comment
Share on other sites

Dear Kayut!

You wrote:

Quote

I have two divs with class demo and want to change their border.

I provided you with a solution to your problem.

Your gratitude:

Quote

I think you didn't read my question properly. Your answer has nothing to do with my question.

It does have much to do with the solution to your problem, however.

Quote

First, this is a forum for JavaScript and not for jQuery

This is the forum for jQuery, as are most forums dealing with Javascript.

Quote

Second, my question is about forEach and your solution has nothing to do with forEach!

Your goal is to iterate across a series of div elements that share a common class.  I provided you with the easiest solution of which I am aware.   Hopefully you have read and understood well Ingolme's explanation, for it is unlikely that you will ever receive another response from me.  To everyone else, when I think of order, I think in terms of multiples of 10.  For example, two orders of magnitude would be some number of a 100 times faster.  For the forum membership please see measurethat.net

jquery_vs_js.tiff

Link to comment
Share on other sites

There is not a jQuery specific forum because jQuery IS! JavaScript but in a framework library of its own.

Yes! it can be done! in very hack-ish way, not ideal, as you lose ability to use some functions associate with JS, and possible more problem issues in future, I.E its a short term fix. Its recommended to stick with the for loop you are currently using, as it works with no potential problem now or in future, and its considered faster from what I read.

Link to comment
Share on other sites

Other than the solution that Ingolme talked about, I'll post the response you got from another forum for completeness, so people know:

Quote

If it actually is an array, then


myClass.forEach(function(element) {
  console.dir(element);
});

If it's an array-like, then


Array.prototype.forEach.call(myClass, function(element) {
  console.dir(element);
});

Sometimes you run into array-like containers in JavaScript that do not have all the Array prototype methods.

As I'm sure you've figured out, that second example will work with the HTMLCollection that Ingolme pointed out, and the first one will work with a NodeList because it has a forEach method.

Quote

Hopefully you have read and understood well Ingolme's explanation, for it is unlikely that you will ever receive another response from me.

That's probably not necessary, if everyone here bailed out at the first sign of a lack of gratitude, no one would be here.  In fairness, the specific question was how to do that with forEach, not jQuery.  jQuery, as a point of fact, is slower and less efficient than vanilla Javascript.  It cannot be any other way, due to the fact that jQuery is written in Javascript.  The upper bound for the speed that jQuery works at is the same upper bound for Javascript, but the lower bound is much lower.  In other words, jQuery can never be faster than vanilla Javascript, only slower (and, in practice, it is virtually never as fast, there is always added overhead with jQuery).  Your screenshot shows an order of magnitude of difference.  Another example is this test.  Finding elements is one of the most basic and often-used operations.  Again, jQuery is an order of magnitude slower:

Quote

getElementById() x 1,976,609 ops/sec ±0.72% (54 runs sampled)
jQuery(#id) x 486,789 ops/sec ±3.63% (60 runs sampled)

getElementsByClassName() x 1,316,751 ops/sec ±0.53% (64 runs sampled)
jQuery(.id) x 218,763 ops/sec ±2.30% (62 runs sampled)

The only reason people use frameworks like jQuery is because it makes development faster.  It makes it faster to actually write the code.  But jQuery will always be slower at execution time.  It took less time to write the code, but more time every time you run it.  Maybe the difference isn't enough to get someone to dump jQuery, but that's a decision for each developer.

Link to comment
Share on other sites

jQuery vs Javascript
 

I am well aware that W3Schools prefers to teach Javascript in its most basic form, and I have learned much about the language as a result, but jQuery does much more than simplify the writing of Javascript statements.  It also corrects for cross-browser discrepancies and clearly separates form and function in its plug-ins. Further, it looks for the simplest way to achieve a task and codifies it.  in brief, on a statement per statement basis, Javascript will always perform better, for the reasons that you have given.  Overall, however, jQuery serves to correct for coding inefficiency.

An important thing that I have learned since I began coding, is that there are often many ways to achieve the same task. 

My gosh!  As a beginner, I know for a fact that switch statements are slower than multiple if-else statements.  Still I use them, for they make it so much easier to understand what I am doing as I do it, and what I have done when I return to it many months later.

Roddy

p.s.

1 x 10 = 10 (a full order larger)

1 x 10 x 3 = 30  (an order and a multiple larger)

1 x 3 = 3 (not an order larger, rather a multiple larger)

Edited by iwato
Link to comment
Share on other sites

jQuery can be useful, even though it's a heavy library to import if you're only doing basic things with it, but that doesn't mean that people should avoid learning Javascript in general.  Many people like to learn or do things for the sake of it, so it's not always helpful to suggest that they use a library instead of learning the fundamentals.

I'm aware of what an order of magnitude is, and jQuery consistently runs an order of magnitude slower than native code.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...