jQuery add class based on page URL with separate classes Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!What is the best way to add options to a select from as a JS object with jQuery?Add table row in jQueryGet current URL with jQuery?How do I modify the URL without reloading the page?How can I select an element with multiple classes in jQuery?Scroll to the top of the page using JavaScript/jQuery?Get class list for element with jQueryRemoving multiple classes (jQuery)jQuery how to find an element based on a data-attribute value?How can I refresh a page with jQuery?

How can I introduce the names of fantasy creatures to the reader?

Protagonist's race is hidden - should I reveal it?

Network questions

How to charge percentage of transaction cost?

Kepler's 3rd law: ratios don't fit data

Weaponising the Grasp-at-a-Distance spell

Can a Knight grant Knighthood to another?

Determine the generator of an ideal of ring of integers

Does GDPR cover the collection of data by websites that crawl the web and resell user data

/bin/ls sorts differently than just ls

Assertions In A Mock Callout Test

Converting a text document with special format to Pandas DataFrame

A German immigrant ancestor has a "Registration Affidavit of Alien Enemy" on file. What does that mean exactly?

What's the connection between Mr. Nancy and fried chicken?

Can 'non' with gerundive mean both lack of obligation and negative obligation?

Has a Nobel Peace laureate ever been accused of war crimes?

What helicopter has the most rotor blades?

Does the Pact of the Blade warlock feature allow me to customize the properties of the pact weapon I create?

Reflections in a Square

How do I deal with an erroneously large refund?

Does Prince Arnaud cause someone holding the Princess to lose?

Short story about an alien named Ushtu(?) coming from a future Earth, when ours was destroyed by a nuclear explosion

tabularx column has extra padding at right?

Lights are flickering on and off after accidentally bumping into light switch



jQuery add class based on page URL with separate classes



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!What is the best way to add options to a select from as a JS object with jQuery?Add table row in jQueryGet current URL with jQuery?How do I modify the URL without reloading the page?How can I select an element with multiple classes in jQuery?Scroll to the top of the page using JavaScript/jQuery?Get class list for element with jQueryRemoving multiple classes (jQuery)jQuery how to find an element based on a data-attribute value?How can I refresh a page with jQuery?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I wanted to find a way to extract from the url the classes to be added to the body. I made some attempts but I only managed to get the last piece of the url.
Do you know how I could do?



this is what I tried to do with jquery



var dir= window.location.pathname.split('?')[0].split('/').filter(function (i) return i !== "").slice(-1)[0]
jQuery("body").addClass(dir);


this is what i have:



 http://www.test.com/news/hello/
<body class="hello"></body>

http://www.test.com/news/
<body class="news"></body>


this is what I would like to have



 http://www.test.com/news/hello/
<body class="hello news"></body>









share|improve this question




























    0















    I wanted to find a way to extract from the url the classes to be added to the body. I made some attempts but I only managed to get the last piece of the url.
    Do you know how I could do?



    this is what I tried to do with jquery



    var dir= window.location.pathname.split('?')[0].split('/').filter(function (i) return i !== "").slice(-1)[0]
    jQuery("body").addClass(dir);


    this is what i have:



     http://www.test.com/news/hello/
    <body class="hello"></body>

    http://www.test.com/news/
    <body class="news"></body>


    this is what I would like to have



     http://www.test.com/news/hello/
    <body class="hello news"></body>









    share|improve this question
























      0












      0








      0








      I wanted to find a way to extract from the url the classes to be added to the body. I made some attempts but I only managed to get the last piece of the url.
      Do you know how I could do?



      this is what I tried to do with jquery



      var dir= window.location.pathname.split('?')[0].split('/').filter(function (i) return i !== "").slice(-1)[0]
      jQuery("body").addClass(dir);


      this is what i have:



       http://www.test.com/news/hello/
      <body class="hello"></body>

      http://www.test.com/news/
      <body class="news"></body>


      this is what I would like to have



       http://www.test.com/news/hello/
      <body class="hello news"></body>









      share|improve this question














      I wanted to find a way to extract from the url the classes to be added to the body. I made some attempts but I only managed to get the last piece of the url.
      Do you know how I could do?



      this is what I tried to do with jquery



      var dir= window.location.pathname.split('?')[0].split('/').filter(function (i) return i !== "").slice(-1)[0]
      jQuery("body").addClass(dir);


      this is what i have:



       http://www.test.com/news/hello/
      <body class="hello"></body>

      http://www.test.com/news/
      <body class="news"></body>


      this is what I would like to have



       http://www.test.com/news/hello/
      <body class="hello news"></body>






      jquery html css






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 22 at 13:58









      Luca BellettiLuca Belletti

      619




      619






















          2 Answers
          2






          active

          oldest

          votes


















          1














          The slice method return an array so all you need to do is removing the [0] so that you can have all your classes.



          You should also put 2 as the paramater of slice so that it can take all your classes after your base url.






          var url = " http://www.test.com/news/hello/"
          var dir = url
          .split('?')[0]
          .split('/')
          .filter(function (i) return i !== "")
          .slice(2);

          $("div p").addClass(dir);

          .news 
          color: red;


          .hello
          font-size: 20px;

          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

          <div>
          <p>Hello world</p>
          </div>








          share|improve this answer






























            0














            You are explicitly taking the last element of the array with .slice(-1)[0], try something, you can just use the result of the filter method without the slice call.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55301232%2fjquery-add-class-based-on-page-url-with-separate-classes%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              The slice method return an array so all you need to do is removing the [0] so that you can have all your classes.



              You should also put 2 as the paramater of slice so that it can take all your classes after your base url.






              var url = " http://www.test.com/news/hello/"
              var dir = url
              .split('?')[0]
              .split('/')
              .filter(function (i) return i !== "")
              .slice(2);

              $("div p").addClass(dir);

              .news 
              color: red;


              .hello
              font-size: 20px;

              <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

              <div>
              <p>Hello world</p>
              </div>








              share|improve this answer



























                1














                The slice method return an array so all you need to do is removing the [0] so that you can have all your classes.



                You should also put 2 as the paramater of slice so that it can take all your classes after your base url.






                var url = " http://www.test.com/news/hello/"
                var dir = url
                .split('?')[0]
                .split('/')
                .filter(function (i) return i !== "")
                .slice(2);

                $("div p").addClass(dir);

                .news 
                color: red;


                .hello
                font-size: 20px;

                <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

                <div>
                <p>Hello world</p>
                </div>








                share|improve this answer

























                  1












                  1








                  1







                  The slice method return an array so all you need to do is removing the [0] so that you can have all your classes.



                  You should also put 2 as the paramater of slice so that it can take all your classes after your base url.






                  var url = " http://www.test.com/news/hello/"
                  var dir = url
                  .split('?')[0]
                  .split('/')
                  .filter(function (i) return i !== "")
                  .slice(2);

                  $("div p").addClass(dir);

                  .news 
                  color: red;


                  .hello
                  font-size: 20px;

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

                  <div>
                  <p>Hello world</p>
                  </div>








                  share|improve this answer













                  The slice method return an array so all you need to do is removing the [0] so that you can have all your classes.



                  You should also put 2 as the paramater of slice so that it can take all your classes after your base url.






                  var url = " http://www.test.com/news/hello/"
                  var dir = url
                  .split('?')[0]
                  .split('/')
                  .filter(function (i) return i !== "")
                  .slice(2);

                  $("div p").addClass(dir);

                  .news 
                  color: red;


                  .hello
                  font-size: 20px;

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

                  <div>
                  <p>Hello world</p>
                  </div>








                  var url = " http://www.test.com/news/hello/"
                  var dir = url
                  .split('?')[0]
                  .split('/')
                  .filter(function (i) return i !== "")
                  .slice(2);

                  $("div p").addClass(dir);

                  .news 
                  color: red;


                  .hello
                  font-size: 20px;

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

                  <div>
                  <p>Hello world</p>
                  </div>





                  var url = " http://www.test.com/news/hello/"
                  var dir = url
                  .split('?')[0]
                  .split('/')
                  .filter(function (i) return i !== "")
                  .slice(2);

                  $("div p").addClass(dir);

                  .news 
                  color: red;


                  .hello
                  font-size: 20px;

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

                  <div>
                  <p>Hello world</p>
                  </div>






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 22 at 14:19









                  KnrianoKnriano

                  743521




                  743521























                      0














                      You are explicitly taking the last element of the array with .slice(-1)[0], try something, you can just use the result of the filter method without the slice call.






                      share|improve this answer



























                        0














                        You are explicitly taking the last element of the array with .slice(-1)[0], try something, you can just use the result of the filter method without the slice call.






                        share|improve this answer

























                          0












                          0








                          0







                          You are explicitly taking the last element of the array with .slice(-1)[0], try something, you can just use the result of the filter method without the slice call.






                          share|improve this answer













                          You are explicitly taking the last element of the array with .slice(-1)[0], try something, you can just use the result of the filter method without the slice call.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 22 at 14:05









                          arieljuodarieljuod

                          8,05711222




                          8,05711222



























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55301232%2fjquery-add-class-based-on-page-url-with-separate-classes%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript