Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Looping addClass/removeClass in Javascript

Featured Replies

I spent not a one day for to understand how i can use javascript loop for adding and removing classes.

I added addClass to all elements. But still can't understand how i should add and remove class for one element and after that go to another element. I saw lot's of article how to do this in query each finction, but i don't want to just copy code, i want understand the logic.

 

My code is simple.

 

Please, give me some advice, how i can add red line to one element (active class), when delete it and go to another element for to achive the same effect? If possible, provide me a little explanation.

Thank you!

<p class="active">Parrot0</p>
  <p>Parrot1</p>
  <p>Parrot2</p>
  <p>Parrot3</p>
  <p>Parrot4</p>
  <p>Parrot5</p>
.active {
background:red;
padding:10px;
}
var p = $("p");



function removeAddClass() {

for (var i = 0; i < p.length; i++) {
  $(p[i]).addClass('active');
}
  }
removeAddClass();



  • Author

I found this great article and solved my problem.

But still can't understand in what case i need to use loop on js.

I am continue seaching)

What exactly are you trying to achieve? Sorry, I might just be tired! :D

 

Edit: Your JS above could be simplified to:

 

$("p").each(function(){
  $(this).addClass("active");
});

Edited by andy9l

What exactly are you trying to achieve? Sorry, I might just be tired! :D

 

Edit: Your JS above could be simplified to:

 

$("p").each(function(){
  $(this).addClass("active");
});

 

of even simply:

 

$('p').addClass('active');

 

:)

 

Loops are used often but not to select all the elements at once and perform the same operation on them, that would be inefficient. An example where a loop would be used with the DOM would be an equal heights, you'd find all the elements that have a class say .js-equal-height, then loop over them finding the tallest one, then setting the height on all those elements to equal the tallest. Here an each loop would be used.

 

 

The other types of loops are generally used for things like looping over an array (for loop) or looping through the properties of an object (for in)

 

Here's an example of an equal heights module that I wrote:

(function($) {
    WASABIWEB.equalHeights = {
        init: function(group) {
            "use strict";
            var elementsArray = [],
                elements,
                count = 0,
                el,
                iPosition,
                elPosition,
                elHeight,
                iHeight;
            if (group) {
                elements = $(group).find('.js-equal-height');
            } else {
                elements = $('.js-equal-height');
            }
            // reset the heights of all the selected elements
            elements.height('auto');
            elements.each(function() {
                // add each element to the array.
                elementsArray.push($(this));
            });

            for (var i=0, x = elementsArray.length; i<x; i++) {
                elements.each(function() {
                    el = $(this);
                    iPosition = elementsArray[i].offset().top;
                    elPosition = el.offset().top;
                        // grab the top positions of the elements
                    if (count !== i) {
                        // check it's not the current item
                        if (iPosition === elPosition) {
                            // two elements are in the same vertical position.
                            iHeight = elementsArray[i].outerHeight();
                            // set the heights equal to the tallest.
                            elHeight = el.outerHeight();
                            if (iHeight >= elHeight) {
                                el.css({'height' : iHeight});
                            } 
                        }
                    }
                    count ++;
                });
            }
        }
    };
    WASABIWEB.equalHeights.init();
}(jQuery));

 

of even simply:

 

$('p').addClass('active');

 

:)

Ha, well yes but I assumed the loop was needed for some reason, hence the topic ;)

Has this been fixed and answered for you? It would be great to start seeing people cliking answered when they have got what they came here for. Would help people in need easier to find.

 

Click on answered if you don't need any furthur assistance.

  • Author

Thank you for answers! Andy9l, i wanted to achive this effect. And i found this article about loop and just adopt this code for myself. But i was very sad because of that :) I thought that loop goes from one element to another and perfom task. For instance - addClass/removeClass from one element, then go to another element and do the same. I thought that counter and loop is the same things. I am confused)) I tried

function removeAddClass() {

for (var i = 0; i < p.length; i++) {
  $(p[i]).addClass('active').removeClass('active');
}
}
removeAddClass();

but it just removed active class.

 

And may i ask the question. Why i need to use each function when i can simply add smth to all elements?

 

rbrtsmith, thank you twice for answer! I start understand in what case i should use loop and what way. In articles i see how i

should write loops but no one tells for what.) i also read about init: function() and now i can see in your code that its good way to write js. In my main.js i use short hand-made patterns. But i think its more clean way to make variable for one my task and put all functions inside this variable like in your example.

Edited by fleur

I recommend, if you wanna get good with JavaScript you sign upto codeschool and go through their JavaScript roadtrips, they really helped me to understand the language, and then you can start manipulating the DOM with it. I think you're gonna really struggle to learn JavaScript from random tutorials.

  • Author

I was in and i like it lessons. i will try codeschool too, thank you.

I understand your code. But if possible, tell me for what you need count ++; if there is already exist

 

for (var i=0, x = elementsArray.length; i<x; i++)

 

sorry for maybe fool question. the counter is most complicated thing for me now.

the ++ operator takes the variable, in this case i and increases it by 1. You need this to move the loop pointer to the next item in the array for each itteration of the loop, otherwise the loop would keep executing the code on the same array element, and the loop would never exit because 'i' would never be larger than 'x' (x being the length of the array)

Edited by rbrtsmith

  • Author

I understand.

if (count !== i) - check that count is not 0 and goes to the next item (count++). And so for each elements.

Thank you! I will play with your code for different task. It will help me to learn loop.

To be honest I don't think my code is the best place to learn how to use loops, it is quite a complex example. Like I said previously your time would be better spent over at CodeSchool, it was my go-to resource while I was learning and I still visit to refresh.

Edited by rbrtsmith

  • Author

Thank you! I will too. :)

  • Author

I was playing around your script. I don't understand what $(group) does (maybe parent selector?). And finally i went with this script for equal block heights. It seems to me i start to understand loops.)

Yeah that one is a bit more simple as it works with groups, giving all the children an equal height, mine works differenly, because when you want things to be equal height you generally want them to be on the same row (The same offset from the top of the document) similar boxes on other rows usually don't need to be the same height as boxes above them. So mine does that, and as an added benefit say when you go onto mobile and all your boxes stack vertically, well then they will just collapse to the height dictated by their content because they now all have different offsets from the top.

 

Both scripts are useful in different scenarios it depnds what you are trying to do. I usually roll with mine because that scenario is more commona and works better with responsive based layouts.

 

Again I wouldn't recommend you learn too much about loops, try to learn the actual language rather than dom manipulation with jQuery. Like I said CodeSchool is a good place to start. Codeacademy is probably the best resource that is free,

  • Author

Yes, I understand. Your original script is complicated, I didn't understand all details, that's why i make light version:)

You know, i read Flanagan's book, after that i passed Codeacademy course. I understand theory, but when i tried to make my own script i can't do nothing. But from this time i go deeper in your script i start to understand the theory, which i read from book. I need practise. I made another one script today at office and solved another one my problem. I start to understand jq. That's why i hope that you and other experienced programmers will continue answer questions on this forum, post scripts and explanation.:) I think it's very userfull not only for me, but for all developer who wants to go deeper in js (jq), because its the most important programming language for people who make modern sites.

  • Author

I was playing around loops and went with this script.

<p>red</p>
<p>blue</p>
.red {
    color:red;
}
var p = $('p');
var count = 0;


for (var i = 0; i <= p.length; i++) {
  setDelay(i);
}

function setDelay(i) {
    if (count) {
  setTimeout(function(){
      $(p[i]).addClass('red');
  }, 1000);
        }
    count++;
}

http://jsfiddle.net/u3em2hzs/8/

 

I was playing for a long time but still didn't get - why my loop starts from the second p? Where is my mistake? I would like loop starts from first p, then after a sec goes to the second p. I will be very greatful if you can point me to the right direction. Thank you!

Edited by fleur

Have you gone through the CodeSchool js tutorials like I suggested? You're gonna struggle to learn js properly by jumping straight into dom manipulation and jQuery without properly understanding the language first. Once you have gone through the 3 roadttrips they have, then start playing around with jQuery and the DOM.

 

For practsicing loops avoid messing around with the dom just use the language. why don't you try to output a bunch of multiplaction tables to the consoie for instance.

It is your "count" variable that is the problem. The first time the function is called count is equal to 0 and you are just evaluating (count) which seems to be equal to false when the value is 0.

I don't know what the purpose of this variable is but if you evaluate it as (count != null) which check if the variable has any value incl 0 then it will work.

 

http://jsfiddle.net/Nillervision/x43u3s2m/1/

  • Author

rbrtsmith, thank you for advice! I will learn CodeSchool. And Douglas Crockford videos, like you suggested on forum ( i am already watching). I like your advice about learning native js loops first and only then manipulation with DOM and will follow it this evening.

 

Nillervision, now i understand my mistake. Thank you for lesson!

 

Lyndsey, thank you very much for scripts! It exactly what i wanted to achive! :) Now i understand the rules. I can't write the same code by myself now (still complicated for me)) but i understand the base. Its important for me.

The reason I say to learn the language before you start to manipulate the DOM is because the DOM is merely an API, and a terrible one at that, and I think trying to learn the DOM API at the same time as you try to learn the language will make it more difficult to grasp the core concepts of the language. This is why most good JavaScript publications do things in that order.

 

The Crockford Videos are very good, but they will, at this stage probably confuse you as they go very advanced in parts, due to the fact he is one of the most advanced JS developers around. The codeschool course starts off with the absolute basics and then goes into more intermediate stuff like closures etc. Crockford Vids are great to build on knowledge gained from CodeSchool.

The reason I say to learn the language before you start to manipulate the DOM is because the DOM is merely an API, and a terrible one at that, and I think trying to learn the DOM API at the same time as you try to learn the language will make it more difficult to grasp the core concepts of the language. This is why most good JavaScript publications do things in that order.

 

The Crockford Videos are very good, but they will, at this stage probably confuse you as they go very advanced in parts, due to the fact he is one of the most advanced JS developers around. The codeschool course starts off with the absolute basics and then goes into more intermediate stuff like closures etc. Crockford Vids are great to build on knowledge gained from CodeSchool.

 

I started the JavaScript path course on Code School to get a feel for what the training is like. I'm impressed so far.

 

I started the JavaScript path course on Code School to get a feel for what the training is like. I'm impressed so far.

 

You'll enjoy Roadtrip 3 and JavaScript best practices. I think the first two will not be very challenging for you. I found on the 3rd roadtrip I had to really understand the material to pass them.

  • Author

CodeSchool is a good place, i see. Only one thing - monthly limit. I never know what time i will go home from work and how much time i can spend on learning.)) I am thinking about to take off-line JS course on Saturday (4 lessons per month) exactly for designers. Anyway, i will decide after holiday. Sorry for my beginner's questions. Till holiday i will continue mostly learning from posts here. This forum is very userful for me in this field :)

CodeSchool is a good place, i see. Only one thing - monthly limit. I never know what time i will go home from work and how much time i can spend on learning.)) I am thinking about to take off-line JS course on Saturday (4 lessons per month) exactly for designers. Anyway, i will decide after holiday. Sorry for my beginner's questions. Till holiday i will continue mostly learning from posts here. This forum is very userful for me in this field :)

 

As far as I know there is no monthly limit on codeschool. You pay $30 pm and you use as much as you like. $30 is a steal for the quality of the material.

  • Author

https://www.codeschool.com/enroll

$29

Per Month

 

I don't know if month will be enough for me that's why i am thinking about Saturday course. But anyway i will decide after new year. Till this time i am learning forum and your blog. I find both is very userful.

Edited by fleur

You will need more than one month, I've been signed up for well over a year. JavaScript takes hundreds of hours to get good at, and many thousands to master. I'm probably quite close to a thousand but still there's lot's more to learn.

 

I'd recommend it over a weekend course for those reasons. and you'd be hard pressed to find better material to learn from. I spend around $100 a month on online based learning and it's been well worth the money, and I'm sure my investment will yield a very positive return. Even when I consider the time invested which is worth a lot more than the money. The benefit to online learning is that if they have 10,000 subscribers that's a lot of money and their budget for material will be far higher, they can afford to keep more upto date, offer better - more experienced tutors, better production value etc.

 

My blog isn't really a 1 stop resource to learn from, I wont be posting beginner articles or intros to things as such. It's merely a place where I can post things I learn, kind of like a notepad of my findings. Some of it will be useful for sure, but I highly recommend you learn from a complete resource that covers everything you need to know, and use my blog and other developer blogs to build upon that knowledge.

  • Author

I agree with you on 100%. And now i understand that for learning how to build IOS and Android apps ( i am going to learn after new year) i need to know 'clean' js. In this article author tells that '...developers will move from monolithic frameworks like Angular.js and Ember to a ‘pick n mix’ of small, dedicated libraries'. I don't agree with him on 100% (its better one stable framework for common tasks, i think), but i see another one argument for to learn js. There is lots of frameworks, but one stable programming language.

 

Today i was playing with your code for styling select element. I put a little changes: make class names shorter, switch state name from BEM to SMACSS (for to make shorter) and of cause! translated js to my lovely jq:)

 

http://codepen.io/Lucky/pen/ZYQyeo

 

i understood the logic and it made manipulation with DOM for me much more easier.

 

You know, it was joyful time for me with lots of new information!

 

I am waiting for your next userful posts.

Edited by fleur

I wouldn't worry too much about shorter classnames. When things get Gziped they make little difference. What is important with classnames is that they are not tied to the content and that they are descriptive for any developer looking at them. BEM is a very good system for describing css objects, you can tell from within the CSS if part of an object is a child or if it is a modifier. You also get very low specificity. BEM is an adition to the SMACCS standard, and a lot of what I do is based on SMACCS you don't need to pick one or the other. The example I put on CodePen using BEM allows you to nest the Sass selectors without increasing specificity.

.parent {
  width: 100px;
  .child {
    width: 80px;
    .grandchild {
      width: 40px;
    }
  }
}


COMPILES TO
.parent {
  width: 100px;
}
.parent .child {
  width: 80px;
}
.parent .child .grandchild {
  width: 40px;
}

That's bad. Using BEM you can do this

.parent {
  width: 100px;
  &__child {
    width: 80px;
    &__grandchild {
      width: 40px;
    }
  }
}


COMPILES TO
.parent {
  width: 100px;
}
.parent__child {
  width: 80px;
}
.parent__child__grandchild {
  width: 40px;
}

That is far better as each selector is still only one class, where the previous example the last selector contained 3 classes, we can still see from looking at the code that these elements are nested within one another, so we get a good idea of what the HTML might look like.

 

 

There's no need to convert the vanilla JS into jQuery. jQuery is JS.

 

I think you'll really struggle to learn both JS, android and IOS development at once. stick at one and get really good at it. I personally see the useage of native apps start to fall against web apps. The latest Black Friday stats show that 97% of mobile purchases were made through web apps / sites vs 3% purchased from native store apps. I'm putting all my efforts into JS as that's where I see the future, there is also JS on the server side with Node. I'd hate to spend the next 2 years learning Objective C for IOS only to find that demand for native iPhone apps drops.

Edited by rbrtsmith

  • Author

Thank you for explanation about BEM. I understood it, that's why i liked to play with your code. I see the good logic in your js script (one goes after another). It helps me understand.

I read this article about combining OOCSS, SMACSS and BEM, but it's more userful when i can see the rules in your code and have practice.

 

------------

There's no need to convert the vanilla JS into jQuery. jQuery is JS.

------------

Of cause, i agree. I just wanted to check myself if i understand your code on js. Its only for my learning.:)

 

About internet shopping i agree with you on 100%. I need big picture for to see what i will buy. It's impossible in mobile. But most of people use mobile phones and web dev should has some knowledge. People use mobile not only for to buy something. Add to that that every company in our country, who hire developers, wants them to be familiar with mobile dev. I am afraid to be out of date. :) I read this article about good learners and decided to divide my time on three parts: 40% - native JS, 40% - Jquery, 20% - frameworks for mobile developing. I am planning to jump into frameworks and after some time (if Objective C will still be used) i will go deeper inside special programming language.

Edited by fleur

Thanks for linking to the article. I'll give it a read later and perhaps I'll learn something from it too.

 

As for mobile dev -- responsive web based apps work totally fine in mobile. I say that mobile app useage is gonna start declining, it's more expensive to develop for, you need people to download your app, vs just visit your webapp in the browser. As the figures are showing, webapps are converting better than native apps.

If I were you I'd get good at Js and jQuery, then a framework like angular along with Node.js Then you can use js to power everything even on the server(Node) obviously it's your choice but that is what I'd advise -- and that is what I myself am doing.

  • Author

I am so happy that i was starting this topic, cause now i understand where i should move. :) After JS and JQ i will learn new version of angular ( i read its different from the prev version) along with Node.js. And i hope i will learn Tween Max and canvas too. Thank you for all your great advices! I am only web dev in our small company and no one can point me to the right direction.:) I am very happy to have a right path now. And i hope i will see your next blog post soon and can play around code.

I am so happy that i was starting this topic, cause now i understand where i should move. :) After JS and JQ i will learn new version of angular ( i read its different from the prev version) along with Node.js. And i hope i will learn Tween Max and canvas too. Thank you for all your great advices! I am only web dev in our small company and no one can point me to the right direction. :) I am very happy to have a right path now. And i hope i will see your next blog post soon and can play around code.

 

Glad you have some direction now. Canvas is part of Js, but you can do similar stuff with SVG as well. I'm not sure which one might win-out or if they will continue to co-exist. Im recommend learning to use them both.

  • Author

Thank you for advice! I am continue learning JS and Jquery. After that i will go deeper in Angular and Node. And after that time i think we will see where web will be move and what stuff will still exist. :) But in any case i will have a look at both canvas and svg, cause i need this for design and like it.

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.