skip to Main Content

I’m working with a script that calls information from members of certain "member groups" (each defined as a class) to paste into a page.

There are 11 "membergroup" classes and I want the script to call from 5 of them. Right now, I have the script fully functioning, but it only can call for one at a time. I’m not sure how to make it multivariable.

   var len = $('.mg3').length;
                $(`.mg3`).each(function (index) {

(the rest of the script that pulls information from users with that class) 

This is the piece that calls from 1 membergroup at a time, here mg3. I would want it to call from m3, mg4, mg5, mg6, mg7 at the same time. How can I do that?

I tried:


   var len = $('.mg3', '.mg4', '.mg5', '.mg6', '.mg7').length;
                $(`.mg3`, `.mg4`, `.mg5`, `.mg6`, `.mg7`).each(function (index) {

but it just broke the script completely… I’ve never worked with multivariables before and am still new to scripting.

2

Answers


  1. I am guessing this is Jquery syntax. (tell if not)
    I think you can select different classes by adding a coma between them :

       var len = $('.mg3,.mg4,.mg5,.mg6,.mg7').length;
       $('.mg3,.mg4,.mg5,.mg6,.mg7').each(function (index) {

    NB : for the ".each", if it doesn’t work, you can try :

    $('.mg3,.mg4,.mg5,.mg6,.mg7').toArray().each(...

    However, this obviously work only if your code is supposed to do the same thing with these elements.

    Hope this helps…

    Login or Signup to reply.
  2. For jQuery’s each, you will want to pass each class separated by a comma within the same string.

    Since we don’t know what your actual each function includes, here is a basic sample that checks if the $(this) in the loop has the class so you can do something different if need be. If you don’t need to handle that way, you can ignore it and just reference $(this) as the element in the loop.

    $(`.mg3,.mg4,.mg5,.mg6,.mg7`).each(function (index) {
      if($(this).hasClass("mg3")){
        console.log("mg3");
      }
      else if($(this).hasClass("mg4")){
        console.log("mg4");
      }
    else if($(this).hasClass("mg5")){
        console.log("mg5");
      }
      else if($(this).hasClass("mg6")){
        console.log("mg6");
      }
      else if($(this).hasClass("mg7")){
        console.log("mg7");
      }
      else if($(this).hasClass("mg8")){
        console.log("mg8");
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="mg3">3</div>
    <div class="mg4">4</div>
    <div class="mg5">5</div>
    <div class="mg6">6</div>
    <div class="mg7">7</div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search