What could be causing this jQuery to malfunction?

Having trouble with the functionality of hasclass and this.addclass.

if ($('.sidebar-menu-container li').hasClass('current-menu-item')) {
    $(this).addClass('expanded');
}

Check out this CodePen for reference.

Answer №1

$('ul.sidebar-menu-container li.current-menu-item').addClass('expanded')
.expanded {
  background:blue !important;
  border: 2px solid yellow;
}
li {
  background: #ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="sidebar-menu-container">
<li class="current-menu-item">asdasdasdasd</li>
<li>asdasdasdasd</li>
</ul>

  1. Take note that the parent of LI is UL
  2. No iteration required here

Answer №2

Your code is not functioning properly because you have used $(this) inside document.ready, causing it to refer to the document rather than the ($('.sidebar-menu-container li'). When using this outside any function, it refers to the global object.

To fix your code:

$(document).ready(function($) {

$('.sidebar-menu-container li').each(function(){
 if ($(this).hasClass('current-menu-item')) {

    $(this).addClass('expanded');
  }
})
 
});
.expanded {
  background:red !important;
  border: 1px solid green;
}
li {
  background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar-menu-container">
<li class="current-menu-item">asdasdasdasd</li>
<li>asdasdasdasd</li>
</div>

Alternatively:

jQuery(document).ready(function($) {

$('.sidebar-menu-container li.current-menu-item').addClass('expanded')
 
});
.expanded {
  background:red !important;
  border: 1px solid green;
}
li {
  background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar-menu-container">
<li class="current-menu-item">asdasdasdasd</li>
<li>asdasdasdasd</li>
</div>

Answer №3

When using the selector $('.sidebar-menu-container li'), it retrieves multiple elements. If any of those elements contain the class current-menu-item, then the condition will evaluate to true. Instead of utilizing a loop, you can simply use this concise code:

$('.sidebar-menu-container li.current-menu-item').addClass('expanded');

This code targets all li elements with the .current-menu-item class and applies the expanded class to them. jQuery handles this without requiring any loops or conditions.

Answer №4

Your code is returning multiple elements, which could be causing the issue. Try modifying it like this:

jQuery(document).ready(function($) {
  $("li").click(function(){
    if ($(this).hasClass('current-menu-item')) {
      $(this).addClass('expanded');
    }
  });
});

Answer №5

In my opinion, it should be fine to utilize the following code:

$('.sidebar-menu-container li.current-menu-item').addClass('expanded');

The conditional statement is unnecessary.

Answer №6

$(document).ready(function() {
$('.sidebar-menu-container li.current-menu-item').addClass('expanded');
});
.expanded {
  background:red !important;
  border: 1px solid green;
}
li {
  background: #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sidebar-menu-container">
<li class="current-menu-item">asdasdasdasd</li>
<li>asdasdasdasd</li>
</div>

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

Utilizing Odometer to pass a variable to jQuery

I'm interested in incorporating a jQuery odometer into a master page to display dynamic information. I found a helpful resource for this at this link. To achieve this, I need to fetch data from a SQL Server database using C# and then pass it to the J ...

Circle a component around another on the vertical axis (z-index)

A plugin caught my eye some time back, but I'm having trouble locating it. This nifty tool operates by positioning an element behind another one, then smoothly sliding it to the right. After that, it changes the z-index so the element appears larger i ...

What is the best way to click on a specific webElement in a group of webElements using Python Selenium?

After discovering how to locate a subelement of an element using Selenium in python through this informative Stack Overflow post, I am now eager to take my skills to the next level. Selenium Get WebElement inside a WebElement My goal is to be able to exe ...

What determines why the input value is restricted to being of type string?

In my ReactJS component, I am struggling to set the state value as an integer using setState. This is causing issues with the radio button not being checked. constructor(props) { super(props); this.state = { frequency: 1, } handleSelectChange(eve ...

When using Axios to GET from a local PHP file, it only retrieves the code instead of running

I've run into an issue accessing the API as it has CORS disabled, requiring me to make requests on the server side. Currently, I'm using React and Axios to send a GET request to a local php file that should trigger cURL execution. However, instea ...

Every DIV is filled with HTML and CSS

My navigation bar currently has icons placed at the center of a DIV, but I would like to fill up the entire DIV without any spaces left on the sides. The HTML code for the DIV containing the icons is as follows: <nav class="navbar navbar-expand navbar ...

What should I do when the ng-click event doesn't open a new window

<p ng-click='window.location.href="{{data.url}}"''>{{data.name}}</p> Is there anything incorrect about this code snippet? I attempted using onclick as well, but encountered an error in the console. ...

Is it possible to apply varying CSS styles depending on the parent element's class?

Apologies for the poorly worded question, but I am struggling to find the right terms to convey my query. Let me attempt to explain... Is it feasible to apply different css styles based on the classes assigned to the containing element? For example: < ...

Obtaining the complete JSON array in string format

I am currently using Fine Uploader to pass parameters in this way callbacks: { onSubmit: function(id, fileName) { this.setParams({ a: 'adm', b: '126', c: { fileID: id, ...

Learn how to extract an ID created with AngularJS using JavaScript

I have a piece of code that generates multiple divs using ng-repeat and assigns each one an id based on a specific value. <div ng-repeat="item in $scope.items"> <div id="ajs-{{item.title}}">{{text}}</div> <script> v ...

What are the steps to modify the text color in WKWebView?

I've customized my ViewController to include a WKWebView, where I load my content from both .html and .css files. The result resembles a controller for reading books within the Apple Books app. do { guard let filePath = Bundle.main.path(fo ...

Tips for recognizing hyperlinks within a block of text and converting them to clickable links in Angular 2

My task is to create clickable links within a paragraph of strings. I tried using a custom pipe, but seem to be missing something essential. Here's my attempt: import { Pipe, PipeTransform } from '@angular/core'; import { DecimalPipe ...

Having an issue where $.ajax is unexpectedly redirecting

Today I delved into the world of AJAX, and I must say, it's pretty fascinating. I have a scenario where users can update information in HTML tables without having to reload the page. It worked flawlessly the first time with this... For clarification ...

The icons in webviews on mobile apps (iOS and Android) fail to render correctly

My font icons are behaving inconsistently on webkit-based mobile browsers when used on mobile devices. When hovering over the span on a desktop browser, the icon properly fills its container: https://i.sstatic.net/qzrmz.png However, when hovering over t ...

The picture is malfunctioning

I am experiencing an issue with the placement of an image in my HTML code. When I place the image inside the nav element, it works perfectly fine. However, when I try to put it inside the body or header elements, it doesn't display properly. I am new ...

How to create a self-contained div in VueJS using Tailwind CSS without affecting other elements

I'm feeling completely overwhelmed right now. Attached is a picture showing the issue I'm facing: The user list layout is on the right The chat content in the middle should be scrollable vertically The bottom div should stay fixed in place witho ...

When the webpage first loads, the CSS appears to be broken, but it is quickly fixed when

Whenever I build my site for the first time, the CSS breaks initially, but strangely fixes itself when I press command + s on the code. It seems like hot reloading does the trick here. During development, I can temporarily workaround this issue by making ...

Form_Open will automatically submit - Ajax Submission in CodeIgniter

I am facing an issue with submitting my form via Ajax. Despite setting up a function to prevent the page from refreshing upon submission, it seems like the form still refreshes the page every time I click submit. I even tried creating a test function to lo ...

What is the best way to send an event handler to a sibling component?

I am facing a situation where I have an eventHandler that needs to be handled by its sibling component. The <Brains /> component contains several properties (such as this.randomNumber = 555 inside the constructor) that are required for the proper fun ...

Prevent Image Distortion in HTML and CSS

Is there a way to prevent a background image from stretching in html/css? Take a look at the current code below, where the image behind a button appears like this: #backImage6{ /*@editable*/background-image:url(https://images.unsplash.com/phot ...