Iterating over the IDs of div elements using jQuery loop

Currently, I am working with a bootstrap accordion and attempting to retrieve the ID and HREF values for each individual accordion using jQuery. Here is the code snippet that I have been utilizing:

$('.room-loop').each(function(id){
    $('.room-loop-a').attr("href", '#'+(id));
    $('.room-loop-body').attr("id", id)
    console.log(id)
  });

However, upon execution, the ID and HREF attributes for all elements with the classes "room-loop-a" and "room-loop-body" are set to 3. Various attempts such as importing a variable ID and incrementing it within the loop have been made, but none of them seem to be effective in resolving the issue. Are there any suggestions or solutions that could potentially address this problem?

Answer №1

To address your issue, consider utilizing the .find() method based on your HTML structure.

$('.room-loop').each(function(id) {
  $(this).find('.room-loop-a').attr("href", '#room' + (id));
  $(this).find('.room-loop-body').attr("id", "room" + id)
  console.log(id)
});

The concern here is that

$('.room-loop-a').attr("href", '#'+(id));
will assign the same href attribute to all elements with the class room-loop-a.

Additionally, it's generally advised not to start an ID with a number. Therefore, I've inserted room at the beginning, but feel free to modify it as needed.

Demo

$('.room-loop').each(function(id) {
  $(this).find('.room-loop-a').attr("href", '#room' + (id));
  $(this).find('.room-loop-body').attr("id", "room" + id)
  console.log(id)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="room-loop">
  <a href="" class="room-loop-a">room-loop-a</a>
  <div class="room-loop-body">
    room-loop-body
  </div>
</div>

<div class="room-loop">
  <a href="" class="room-loop-a">room-loop-a</a>
  <div class="room-loop-body">
    room-loop-body
  </div>
</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

Trigger useEffect after prop has been changed

I'm trying to figure out how I can avoid running an API call in my component on initial rendering. The prop needed for the API call should be updated only after a form submission. Although I have included the prop in the dependency array of useEffect, ...

Whenever I try to relocate my HTML file that references three.js, the three.js library seems to malfunction and stop

Something strange is happening... I recently downloaded three.js into a directory named 'brick': git clone https://github.com/mrdoob/three.js.git which created a subdirectory: brick/three.js/ After navigating to brick/three.js/examples ...

Why do class definitions become unavailable in Javascript due to the semantics of `require()`?

I am encountering an issue with file allocation.js which contains the definition of class Allocation {...}. In another file called test.js, I have included require('./allocation.js'), followed by a = new Allocation;, which results in a ReferenceE ...

Tips for troubleshooting the StaleElementReferenceError in selenium automation

Encountering the persistent issue of receiving the error message StaleElementReferenceError: stale element reference: element is not attached to the page document every time I attempt to extract the text from a page body using Selenium. Numerous attempts h ...

I'm encountering a "confirm" error within the data table. Any suggestions on how to resolve this issue?

When I try to use two datatables columns in confirm, an error occurs when the text 'do you want cancel?' is displayed. The issue seems to be with the text itself and not the code. How should we go about fixing this problem? This is my current cod ...

Checking for Internet Connectivity in Mobile HTML5

Is it possible to check for internet connectivity on a mobile device? Can websockets be utilized to ping a server and determine if the connection is available? I am feeling frustrated as I believed there was a ping function in websockets for client-side u ...

Is it possible for the Observable call in Angular 4 to function similarly to jQuery's synchronous AJAX method?

As I have a business logic function that needs to use HttpGet and I must wait for the result before continuing, jQuery's ajax can handle this easily. But I am curious if Observables have a similar feature? I was hoping for the result to be: John An ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

Returning a 404 Error stating "Invalid request to /api/users/register."

Encountering an issue with proxy connection - unable to determine the root cause despite verifying all routes. Not able to successfully register the user and store data in MongoDB. Seeking suggestions for resolution. Thank you. Attempting to send user reg ...

Tips for adding style to a group of SVG elements:

I currently have an array of .svg icons, each with unique properties that I need to customize: <svg width="24" height="24" viewBox="0 0 24 24"> ... </svg> import styled from 'styled-components'; import Github from 'assets/git ...

Is it possible to trigger a server-side event using jQuery in SharePoint 2010?

For my Sharepoint 2010 application, I have been utilizing jQuery to handle most events on the client-side. However, when it comes to saving data to the Sharepoint list and generating a PDF file with that data, I need to switch to server-side processing usi ...

Capturing user input by detecting the Enter key using jQuery

I am brand new to coding and struggling with capturing user input when the enter key is pressed. Currently, I have a submit button that successfully captures user input upon clicking. <div> <div class="text-area"> <li class=" ...

Is there a way to compel @keyframes to continue playing until it reaches its conclusion even after a mouseout event

Whenever I hover over an element, a keyframe animation starts playing. However, when I move the cursor away, the animation stops abruptly. Is there a way to ensure that it plays until the end? I've tried using the animationend event, but it doesn&apos ...

Tips for modifying AJAX behavior or restricting requests in Wicket

I am looking to prevent updates based on a specific JavaScript condition using AjaxSelfUpdatingTimerBehavior. WebMarkupContainer messagesWmc = new WebMarkupContainer( "messagesWmc" ) ; messagesWmc.setOutputMarkupId( true ) ; messagesWmc.add( ...

Runs tasks asynchronously in a sequential manner

I am attempting to run two functions asynchronously in series using node.JS, but I am struggling with the implementation. Currently, my code looks like this: Function 1: function search(client_id, callback) { clientRedis.keys('director:*', ...

Correcting W3C validation issues is essential

I am encountering errors in my W3C validation process. Even though I have set <!DOCTYPE HTML> for my page, I continue to experience issues as shown in the image below. I have been trying to troubleshoot and resolve these errors without much success ...

Can you explain the significance of the regular expression in a dojo configuration file named dj

As I was working on developing dojo application modules, I came across a regular expression in tutorials. var pathRegex = new RegExp(/\/[^\/]+$/); var locationPath = location.pathname.replace(pathRegex, ''); var dojoConfig = { asyn ...

Guide to Embedding an Image in a List in HTML

How do I resize an image according to the size specified in CSS, and ensure that it fits within a list of items where each item consists of both an image and a name? Currently, my code only displays the image in its original size. for(var i =0; i< o ...

Executing a method to retrieve a value from an empty function in Node.js

I am currently dealing with the code snippet below: function done(err, file) { //handling of code here return "test"; } function process() { retext() .use(keywords) .process(sentence, done); return val; } The proce ...

"Trouble with kendo drop-down list: onclick event not triggering when text is changed

I am currently working with kendo UI and have implemented a dropdown list of checkboxes. The onchange event is triggering when the user clicks on the checkbox, but it is not firing when the user clicks on the text. Thank you in advance for your assistance ...