Tips on incorporating a class into a link by utilizing the next() method in JQuery

Is there a way to locate the next link after an active class within a class and then apply the active class to that new link? I attempted to use the next() function, but it doesn't seem to be functioning as expected.

$("#next").on("click", function() {
  $(".test a.active").next(".test a").addClass("active");
});
.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"><a href="" class="testx active">a</a></div>
<div class="test"><a href="" class="testx">b</a></div>
<div class="test"><a href="" class="testx">c</a></div>
<div class="test"><a href="" class="testx">d</a></div>
<div class="test"><a href="" class="testx">e</a></div>

<button id="next">click</button>

Answer №1

Instead of using a, you can utilize .next for .test

$("#next").on("click", function() {
 const cls = $("a.active");   
 cls.removeClass('active') // remove previous active if you need
 cls.closest('.test').next(".test").children('a').addClass("active");
});
.active{
  background-color:green;
  color:white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"><a href="" class="testx active">a</a></div>
<div class="test"><a href="" class="testx">b</a></div>
<div class="test"><a href="" class="testx">c</a></div>
<div class="test"><a href="" class="testx">d</a></div>
<div class="test"><a href="" class="testx">e</a></div>

<button id="next">click</button>

Answer №2

To find the index of the test div where the a tag has the class active, you can use the following code snippet. Once you have the index, you can add the active class to its children such as the a tag.

Sample Code :

$("#next").on("click", function() {
  var index_ = $("a.active").closest(".test").index() + 1 //get index of div with active class and add 1 
  $(".testx").removeClass("active") //remove from other elements
  $(".test:eq(" + index_ + ") .testx").addClass("active"); //add to the next element
});
.active {
  color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!--place in an outer div-->
<div>
  <div class="test"><a href="" class="testx active">a</a></div>
  <div class="test"><a href="" class="testx">b</a></div>
  <div class="test"><a href="" class="testx">c</a></div>
  <div class="test"><a href="" class="testx">d</a></div>
  <div class="test"><a href="" class="testx">e</a></div>
</div>
<button id="next">click</button>

Answer №3

Your code is not functioning correctly due to the selector being placed inside the next() function, which targets that specific element instead of the intended next element. Additionally, the element "a" does not have a direct next sibling but rather the surrounding div does.

To resolve this issue, modify the code to target the parent div's next element upon triggering the next event, then select the child element "a" and apply the active class. Refer to the updated code below for clarification.

$("#next").on("click", function() {
  $(".test a.active").removeClass( "active" ).parent().next().children().addClass("active");
});
.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"><a href="" class="testx active">a</a></div>
<div class="test"><a href="" class="testx">b</a></div>
<div class="test"><a href="" class="testx">c</a></div>
<div class="test"><a href="" class="testx">d</a></div>
<div class="test"><a href="" class="testx">e</a></div>

<button id="next">click</button>

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

Guidelines for utilizing the php mail() function

It seems that there is an issue with this code when running it on a local host versus a live server. I am attempting to use this code for a mail function, which works on another site but not on this one. I know the code will produce an error on localhost ...

Display the content as a clickable link using Jquery

Here is the view I have created using .NET MVC3: function DisplayingGrid () { var Geo=$('#ddlGeo').val(); var Vertical=$('#ddlVertical').val(); var Month=$('#ddlMonth').val(); if(Vertical=="All") { var Flag=1; ...

What steps should be taken to handle files in the Next JS api?

My goal is to send a docx file to the browser for client preview. I've attempted two methods: const rs = fs.createReadStream(fullPath); res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.docume ...

Navigate to a different page after completing form submission

I am facing an issue with navigating between pages on my website. I have a form that processes data upon submission, and after processing, I want to redirect the user back to the previous page. Currently, my webpage consists of a list of links that lead to ...

Troubleshooting CSS problems with positioning 3 fluid div elements

I am in need of 3 dynamic div containers. container for main content image display container that changes size container on the side with changing width The issue I am facing is that the text needs to be below the image container which has a wider width ...

Comparison between sending JSON data through a form submission versus using jQuery/AJAX

My process involves a basic form that successfully allows me to create a new project using the Asana API <form action="https://app.asana.com/api/1.0/projects" id="newProject" method="post" name="myform"> <input id="name" name="name" type="tex ...

How can you check if a field is blank without allowing any empty spaces to be saved in JavaScript?

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <body> <form id="api_crud_form" name="api_crud_form" action="https://www.google.es"> Name: <input type="text" name="name" id=" ...

What is the method for looping through and inserting objects into an array using JavaScript's $.each function?

As a novice programmer, I am tackling the challenge of transferring four properties from my JSONP array into a new array for each item. $.ajax({ url: etsyURL, dataType: 'jsonp', success: function(data) { if (data.ok) { ...

What is the ideal way to iterate a loop in jQuery while using setTimeout?

Currently, I'm working on a table and attempting to develop a bookmarklet that will automatically click on each row and perform some actions based on a timer. The loading time for each tab is quite long, but when I focus on just one row, the code work ...

Apply a translucent background color to an image element using CSS

Is there a way to create an overlay div using my HTML markup without adding any additional code? I want to add a dark overlay with opacity over the image, but I'm limited in what I can use. background: rgba(0, 0, 0, 0.5); Here is the current marku ...

Is there a way to shift this div to the bottom and incorporate some quirky pop-up squares?

I am struggling to figure out how to move this div to the bottom. Additionally, I want to create temporary pop-up squares (simple divs) in random directions that will disappear after 50ms. My attempt to float this box to the bottom did not yield the desir ...

Calculate the worth of a specific item within an array of objects and save the outcome as a new attribute

I am attempting to calculate the value in each element and then create a new element called "Count". Rule: Count the quantity if the next element has the same "Quantity" value, then add the total to a new element named "Count". I have tried implementing th ...

Tips for making dynamic keys and values in JavaScript arrays

JSON Input Data 0: {"eid":12,"gender":"1","age":1,"pass":["2","1"]} Data 1: {"eid": 11,"gender":"0","age":1,"pass":["1","3"]} Data 2: {"eid":20,"gender":"1","age":1,"pass":["2","3"]} How can we create a new array to store IDs based on the pass numbers? ...

Modifying the values of Highcharts-Vue chart options does not result in any changes once they have been

I recently started incorporating Highcharts into my Vue project using the highcharts-vue library. A) Initially, in pure JavaScript, the following code snippet functions as expected: let b = 5; let data = { a: b } console.log('data', data.a) ...

Having difficulty resolving all parameters for the component: (?, [object Object]) in the Jasmine component Unit Test

While defining a UT for a component with an extended class using i8nService and ChangeDetectionRef, I encountered an error preventing me from instantiating it: Failed: Can't resolve all parameters for BrandingMultiselectComponent: (?, [object Object] ...

Difficulty with spacing in HTML/CSS styling

Here is what I'm currently working on: link to jsfiddle code * { margin: 0; padding: 0; } html { height: 100%; } header, nav, section, article, aside, footer { display: block; } body { font: 12px/18px Arial, Tahoma, Verdana, sans- ...

Is retrieving data from the database causing unexpected additional space to appear in the textarea?

I am facing an issue with a basic php file that fetches information from a MySQL database and displays it inside a textarea. However, when I access the file through browsers, there seems to be extra space at the start and end of the text within the textare ...

Strategies for Repurposing local file.js across multiple Vue projects

I have a file called myfile.js with functions that I want to reuse in multiple vue projects, specifically within the App.vue file. Here is the file structure: -- projec1 ---- src ------ App.vue -- project2 ---- src ------ App.vue -- myfile.js Directly ...

Arranging HTML elements using Jquery sorting

Possible Duplicate: How can I alphabetically sort a list using jQuery? Technology: Asp.net with jQuery. Hello everyone, Summary: I am relatively new to jQuery and have been working on a script that allows the Enter key to move to the next input elem ...

Customize the order of elements in Bootstrap for mobile devices

How can I create a responsive Bootstrap layout with 2 columns and a nested row in the right column? The desired layout is as follows: Desktop Version: --------- | 2 || 1 | | || | | |------- | || 3 | | || | | ...