1

I'm trying to add the class current-menu-item to the following div:

<div class="menu-item menu-item-type-custom menu-item-object-custom jet-custom-nav__item jet-custom-nav__item-6068">

Afterwards it should be

<div class="**current-menu-item** menu-item menu-item-type-custom menu-item-object-custom jet-custom-nav__item jet-custom-nav__item-6068">

This is how my .js looks like so far

jQuery(document).ready(function() {
    if(window.location.href.match('harmonikapuls.com/konto/adressen/rechnungsadresse')){
        $("menu-item.menu-item-type-custom.menu-item-object-custom.jet-custom-nav__item.jet-custom-nav__item-6068").addClass("current-menu-item");
    }
});

Basically I just want not a specific URL but everything after the slug /adressen/ this was just for trying. I call my function over my function.php

mrmoon97
  • 55
  • 6

1 Answers1

0

You must include dots when using the jQuery selector to find elements by class names.

Furthermore, since you're selecting a div that contains all of the named classes, they must not be separated by space, so $(".menu-item.menu-item-type..."). If you separated the class names by space, it would look for the children of the previous class name. See the answer here.

Also, it would be wiser to add a unique id to the div element by adding an attribute id="myDiv" and then use a hashtag in the selector: $("#myDiv") - it would be more efficient and clearer. If you don't want to use an id, you can select the element just by the class that uniquely identifies it, so for example $(".jet-custom-nav__item-6068").

tomashauser
  • 561
  • 3
  • 16
  • Thank you! I'm still in the learning phase. I removed spaces and seperated with dots but somehow it's still not working. – mrmoon97 May 07 '22 at 17:10
  • Did you look whether the element is found? You can check that by `if ($('...').length > 0)`. Also, the `.jet-custom-nav__item-6068` seems to have a randomly generated value at the end. Does the element you want to select have the same number there each time you reload the page? – tomashauser May 07 '22 at 17:19
  • It works now! I called my function wrong in the functions.php as my `$scr` was wrong. Now the only question left how can change the URL to a slug and everything after. – mrmoon97 May 07 '22 at 17:27