What is the best way to choose two <li> elements with multiple classes in my WordPress navigation menu?

I am looking for a JavaScript function that will add the class "current_highlight" when an element with the class "activo2" also has the class "active".

Here is my HTML code:

<div class="navbar-header">
   <button type="button " class="navbar-toggle navbtn_webds btn_webds" data-  toggle="collapse" data-target=".navbar-collapse">
      <div class="navbtn_webds iconbar_webds iconbar-top_webds"></div>
      <div class="navbtn_webds iconbar_webds iconbar-common_webds"></div>
      <div class="navbtn_webds iconbar_webds iconbar-common_webds"></div>
   </button>
   <a id="site-title" class="navbar-brand brand_webds" href="http://localhost/webds" title="" rel="home"> <small></small></a>
</div>
<div class="navbar-collapse collapse">
    <div class="navbar-collapse collapse">
        <ul id="menu_principal" class="nav navbar-nav pull-right ">
           <li id="menu-item-18" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-18">
              <a title="Serviços" rel="m_PageScroll2id" href="http://localhost/webds/#servicos">Serviços</a>
           </li>
           <li id="menu-item-20" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-20">
              <a title="Equipa" rel="m_PageScroll2id" href="http://localhost/webds/#equipa">Equipa</a>
           </li>
           <li id="menu-item-21" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-21">
              <a title="Trabalhos" rel="m_PageScroll2id" href="http://localhost/webds/#trabalhos">Trabalhos</a>
           </li>
           <li id="menu-item-22" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-22">
              <a title="Clientes" rel="m_PageScroll2id" href="http://localhost/webds/#clientes">Clientes</a>
           </li>
           <li id="menu-item-27" class="activo2 menu-item menu-item-type-post_type menu-item-object-page current-menu-item page_item page-item-2 current_page_item menu-item-27 active">
              <a title="Blog" href="http://localhost/webds/?page_id=2">Blog</a>
           </li>
           <li id="menu-item-23" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-23">
              <a title="Contactos" rel="m_PageScroll2id" href="http://localhost/webds/#contactos">Contactos</a>
           </li>
        </ul>
    </div>    
</div>

<!--/.nav-collapse -->

This is my JavaScript code:

$(document).ready(function () {

var CurrentPage = $('#menu_principal li').hasClass('.activo2');
var CurrentPage1 = $('#menu_principal li').hasClass('.active');


function CurrentMenu() {    
    $('.activo2').toggleClass('current_highlight');
}

if ( CurrentPage == true && CurrentPage1 == true) {
    CurrentMenu();
}
});

And here is my CSS:

.current_highlight {background: #fcf2e0; color: #ff9933;}

Answer №1

Remove the dots from classnames:

var CurrentPage = $('#menu_principal li').hasClass('activo2');
var CurrentPage1 = $('#menu_principal li').hasClass('active');

Answer №2

Here's a suggestion to try:

if ($('#menu_main li.activo2.active').length) {
    CurrentMenu();
}     

DEMO

Also, make sure to correct the typo in your code. When using hasClass(), do not include the dot before the class name.

 var CurrentPage = $('#menu_main li').hasClass('activo2');
                                                     ^

Answer №3

When this function is executed, it will search for any li element containing the class activo2 and add the class current_highlight to it. If the activo2 class is not found, it will remove the current_highlight class from all li elements.

$('li').each(function(){
 if($('.activo2').length) {
 $(this).addClass('current_highlight');
 } else {
 $('li').removeClass('current_highlight');
 }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Iterating over an array and displaying elements on the webpage

Struggling to access an array and loop through it, but only able to print out one element instead of all. Need a hint on how to solve this issue. See my code below: let toppingsCount; const burger = document.createElement('div'); const toppingsD ...

What is the best way to eliminate a vertical line from an HTML table?

I am looking to remove specific vertical lines from an HTML table. There are only 3 vertical lines in total, and I want to remove the first and third lines. Below is my code: <html> <head> <style type="text/css"> .table1{ background: ...

Jsonip.com is providing both internal and external IP addresses

I'm utilizing to retrieve the IP address of users. In some cases, it is returning both an internal and external IP as a string separated by commas. I am interested in only obtaining the external IP address. Can I assume a specific order for the retur ...

How can I use cookies to make an HTML div disappear when a button is clicked?

I've been attempting to conceal this message in Vue.js, but so far I haven't had any luck. Currently, I am utilizing the js-cookie library. My objective is as follows: HTML <div v-show="closeBox()"> < ...

The `overflow:auto` property is causing the flex container to overflow due to the size of its fixed width children

Here's a unique CSS puzzle for you all: Imagine the following hierarchy: app container flex container item1 - fixed width(80px) item2 - responsive width(width:100%). MUI Stepper - overflow:scroll, width:100% This structure would look like this: ...

Eliminate every instance using the global regular expression and the replace method from the String prototype

function filterWords(match, before, after) { return before && after ? ' ' : '' } var regex = /(^|\s)(?:y|x)(\s|$)/g var sentence1 = ('x 1 y 2 x 3 y').replace(regex, filterWords) console.log(sentence1) sentence2 ...

Modify a value using jQuery

On my Asp.net webform, I have a label called "LabelTotalNumber". I am looking to update the value of this label every minute using jQuery without having to refresh the form. How can I achieve this? Currently, I am able to accomplish updating the value onc ...

When NextJS calls a dynamic page in production, it redirects to the root page

My Desired Outcome When a user inputs https://www.example.com/test, I want them to receive the content of the NextJS dynamic route /test/index.js. This functionality is successful in my local environment. The Current Issue Despite a user entering https:/ ...

If the navigation menu contains sub-menus, it should slide to the left

I am currently working on developing a navigation menu with four levels of depth. The menu displays three levels at a time, and when the user reaches the fourth level, the first level should move to the left to make room for the second, third, and fourth l ...

After a period of time, NodeJS abruptly crashes while processing a CSV file

Recently, I've been working on a project that involves converting CSV data into XML. To accomplish this, I have been using the fs.createReadStream() method to read the CSV file. However, I encountered an issue where the terminal crashes unexpectedly a ...

methods for sharing real-time data between parent and child components in Angular versions 2 and above

When working with Angular, we are familiar with parent to child communication using the @Input decorator. However, the challenge arises when we need to pass dynamic data from the parent to the child component. Imagine having a 'name' property def ...

Deciphering the principles of Bootstrap

I'm looking to understand more about what Bootstrap is. I know it's commonly used for styling web pages, but could you provide me with a clear explanation? Can big companies like Twitter, Facebook, or YouTube utilize Bootstrap for their platforms ...

Establish height and width parameters for creating a dynamic and adaptable bar chart with recharts

I am currently facing an issue with recharts while trying to implement a BarChart. The setting width={600} and height={300} is causing the Barchart to be fixed in size, rather than responsive. How can I make the BarChart responsive? I attempted using per ...

Issues are occurring with the @font-face css for the Futura Bk BT Bok.ttf font file

Is there a way to incorporate the 'Futura Bk BT Bok.ttf' font into my website using the CSS @font-face rule? Here is a snippet of my current CSS: @font-face { font-family: abcd; src:url('Futura Bk BT Bok.ttf') format('true ...

What is the process for converting a UTC datetime string into the local timezone of users?

I am utilizing Laravel 5.7 for the API and Vue for the frontend development. The API response includes a user's last seen timestamp in UTC format by default, like this: last_seen: "2019-04-17 05:20:37". Laravel API code: $user_details = array( ...

Prevent issues with text overlap in HTML and CSS

My text is overlapping when I resize the window. How can I prevent this? I want the text to resize only if it collides with other elements, or stack under each other if resizing is not possible. problem I've already attempted using flex box setting ...

Guide on transforming 3D obj files into particles using three.js

I've been experimenting with particles in three.js, but I've encountered an issue when trying to convert an obj file (3D model) into particles. Here are the code snippets I've been working with, but so far all my attempts have failed. Does ...

Issue with Aligning Text Inputs and Images in Firefox

I am really struggling with this issue and it's driving me crazy. The problem lies with an image positioned at the end of a text input, styled using CSS. Here is the code snippet: .text_input{ background:url(../images/forms/text_input_back.png) t ...

Expand the search capabilities of WooCommerce products to include custom taxonomies and custom fields

Currently, I am in the process of developing a more advanced WooCommerce search feature that includes SKU, product tag, and product category in the search query. Referencing an insightful solution from this thread on Stack Overflow, I have implemented code ...

The final item in the navigation bar is off-center

After centering all text within the li tags, the last one appears to be slightly closer to the bottom. Below is the code snippet along with an image: *{ margin:0; padding:0; box-sizing:border-box} #hamburgerClick{ displa ...