What is the best method for choosing the next item with jQuery?

I am facing an issue while trying to apply some design on the next element. The error message that I am encountering is:

Error: Syntax error, unrecognized expression: [object Object] > label

Below are my selections for browsing by category:

BROWSE BY
<ul class="list-unstyled">
    <li>
        <input type="radio" id="cat-1" class="category_select" name="category_type" data-category-type="1" value="all_product" checked="checked" />
        <label for="cat-1"><span></span>All</label>     
    </li>
    <li>
        <input type="radio" id="cat-2" class="category_select" name="category_type" data-category-type="2" value="japanese_tea" />
        <label for="cat-2"><span></span>Japanese Tea</label>        
    </li>
    <li>
        <input type="radio" id="cat-3" class="category_select" name="category_type" data-category-type="3" value="black_vinegar" />
        <label for="cat-3"><span></span>Black Vinegar</label>       
    </li>
    <li>
        <input type="radio" id="cat-4" class="category_select" name="category_type" data-category-type="4" value="food" />
        <label for="cat-4"><span></span>Food</label>        
    </li>
    <li>
        <input type="radio" id="cat-5" class="category_select" name="category_type" data-category-type="5" value="cosmetic_health" />
        <label for="cat-5"><span></span>Cosmetic / Health</label>       
    </li>
    <li>
        <input type="radio" id="cat-6" class="category_select" name="category_type" date-category-type="6" value="others" />
        <label for="cat-6"><span></span>Others</label>      
    </li>
</ul>

Here's the JavaScript code I am using:

$('.category_select').on('change', function() {

    var cat = $(this);
    var category_type = $(this).data('category-type');

    $(cat + ' > label').css({'color':'red'}); //the CSS isn't being applied, any idea why?

});

Would appreciate any help or suggestions regarding this matter. Thank you!

Answer №1

To access the next sibling of an element, you should utilize the .next() traversal method.

When concatenating a jQuery object like cat in your code, the selector may end up as [object Object] > label.

$('.category_select').on('change', function() {

  var cat = $(this);
  var category_type = $(this).data('category-type');

  cat.next('label').css({
    'color': 'red'
  }); //why isn't the css applying?

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="list-unstyled">
  <li>
    <input type="radio" id="cat-1" class="category_select" name="category_type" data-category-type="1" value="all_product" checked="checked" />
    <label for="cat-1"><span></span>All</label>
  </li>
  <li>
    <input type="radio" id="cat-2" class="category_select" name="category_type" data-category-type="2" value="japanese_tea" />
    <label for="cat-2"><span></span>Japanese Tea</label>
  </li>
  <li>
    <input type="radio" id="cat-3" class="category_select" name="category_type" data-category-type="3" value="black_vinegar" />
    <label for="cat-3"><span></span>Black Vinegar</label>
  </li>
  <li>
    <input type="radio" id="cat-4" class="category_select" name="category_type" data-category-type="4" value="food" />
    <label for="cat-4"><span></span>Food</label>
  </li>
  <li>
    <input type="radio" id="cat-5" class="category_select" name="category_type" data-category-type="5" value="cosmetic_health" />
    <label for="cat-5"><span></span>Cosmetic / Health</label>
  </li>
  <li>
    <input type="radio" id="cat-6" class="category_select" name="category_type" date-category-type="6" value="others" />
    <label for="cat-6"><span></span>Others</label>
  </li>
</ul>

Answer №2

To easily choose the next label, simply use the id attribute of the input box that has been selected.

$('.category_select').on('change', function() {
        var catId = this.id;
        var categoryType = $(this).data('category-type');
        $("label").css({'color':'black'}) // Reset color to black for all labels
        $("label[for='"+catId+"']").css({'color':'red'}); // Set color to red for the selected label
        
    });

CHECK OUT THIS EXAMPLE ON JSFIDDLE

Answer №3

In order to select the next element, you should use the .next() selector instead of $(cat + ' > label')

$('.category_select').on('change', function() {

    var cat = $(this);
    var category_type = $(this).data('category-type');

    cat.next('label').css({'color':'red'}); //the correct syntax for selecting the next element in JavaScript

});

I hope this explanation has been helpful to you.

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

I prefer to have the links activate when the mouse hovers over them, rather than when hovering over empty

Is there a way to prevent the bottom links (music, contact, archive) from being highlighted when the mouse hovers over the empty space between them and not just on the actual links themselves? I want the mouse to only react to the links it hovers over and ...

Binding arguments to child functions within Vue components

When working with React, it's a common practice to bind parameters for child components in the following manner: <Child onChange={e => doThing(complex.variable.inParentScope[3], e.target.value)} foo="bar" /> In Vue, I want to ach ...

Player using unexpected options instead of Video.js options

I have created a basic HTML page with a small JavaScript snippet to function as a playlist, and it was working perfectly fine. However, when I integrated Video.js into the mix, an issue arose. Sometimes, upon reopening the page, the player fails to load p ...

After using driver.execute_script, the variable results in nil

Attempting to retrieve a lengthy string of URLs separated by commas is proving challenging. The code functions correctly in the console, but when running the script, the ruby variable urls_list remains nil. require 'rubygems' require 'selen ...

Phonegap - Retaining text data in a checklist app beyond app shutdown

This is my first time developing an app with Phonegap. I am looking to create a checklist feature where users can input items into an input field. However, I am struggling with figuring out how to save these items so that they remain in the checklist even ...

"Optimizing the placement of a range slider for pricing options

As a beginner in HTML, CSS and JS, I recently faced the challenge of creating a price slider range on a website. However, I am struggling with repositioning it. After copying the code from this link, I noticed that the slider is positioned at the top of th ...

Illuminate specific areas of a mapped image upon hovering over text on a webpage

Scenario: There is an image on the page with various mapped areas. A list of text elements is also present on the page. Desired functionality: Hovering over different text items in the list should result in highlighting corresponding areas on the mappe ...

Creating a dynamic onclick function that depends on a variable passed from a while loop in PHP

If you're familiar with PHP, I have a scenario for you. Let's say there's a list of items generated using a while loop in PHP. Each item has a sub-list that should only appear when clicked on. I tried using the onclick function in jQuery but ...

Prevent Button Click in ASP.NET After Validating Regular Expression in Textbox

How can I ensure that the asp button is disabled only after the user submits the form with the correct regular expression? Below is the form code: <asp:TextBox ID="TextBox2" runat="server" placeholder="Email" class="form-control" type="email" Font-Siz ...

The checkbox remains unchecked after clicking on the button

I am attempting to add checkboxes before the list items in a listview on my page. When I click on the "edit" button, the listview successfully adds the checkboxes before the list items. However, when I try to click on the checkboxes, the page automatical ...

PhpStorm 2019.2 introduces Material UI components that have optional props instead of being mandatory

My PhpStorm 2019.2 keeps showing me a notification that the Button component from Material UI needs to have an added href prop because it is required. However, when I refer to the Material UI API, I see something different. Take a look at this screenshot: ...

What is causing the VueJS template ref to be undefined when dealing with multiple divs

I have been working on a simple Vue component and I am trying to access the DOM element from the template. The initial component works perfectly: <template> <div ref="cool">COOL!</div> </template> <script> export ...

Error: No targets with the name "taskname" were found for the custom Grunt task

Just recently, I decided to create my own custom task and here's the process: Started by making an empty folder named "custom-tasks" in the Document Root Next, I created the actual task file: "mytask.js" Implemented the functionality required for th ...

Printing form data with values in CodeIgniter

Recently, I tackled the challenge of creating a page with multiple forms in view using codeigniter. My goal is to implement a popup window for printing the data from these forms, complete with a print button. However, I am struggling with the process of ...

Tips on transitioning from Modal1 to Modal2 in Ionic after a successful submit button press?

My survey app requires users to fill out a form and click the Submit Feedback button. Upon successful submission, a message saying "Feedback submitted successfully" should be displayed in Modal2, which is inside another modal named (Modal1). However, being ...

Utilize a standard PHP script for every subdirectory within a domain

I'm currently working on a website and the design I'm using involves changing the URL in the address bar using the history API when the page content changes through JavaScript and AJAX. However, I also want each "page" of the website to be access ...

I am attempting to activate the "about us" button on the website. I have successfully included the path and added a router link to the containing div of the button. However, there seems to be something

In my app, the first step involves specifying the path in the routing module. Following that is defining the home component, then the app component, and finally creating the button using HTML. Setting up the path in the app.routing.module.ts file <div ...

Having trouble updating text in a PDF using NodeJS and hummus library

How can NodeJS be used to replace a string in a PDF file? offers a solution for text replacement in a PDF document. However, when applying the same code, an issue arises where the replaced text is visible in the source code of the PDF but does not render p ...

Tips for effectively implementing an Ajax request with JavaScript when the page loads

I have been developing a shopping cart application that utilizes local storage to store the items added by users. The challenge I'm currently facing is populating the page with the user's cart items stored in local storage when they navigate away ...

Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in ...