I need help figuring out how to mention an id using a concatenated variable in the jquery appendTo() method

Using jQuery, I am adding HTML code to a div. One part of this code involves referencing a div's ID by concatenating a variable from a loop.

$(... +
    '<div class="recommendations filter" id="recCards-'+ i +'">' +
    '<div><h5>Recommended Cards</h5></div>' +
        '<ul></ul>' +
    '</div>' +
  ...
 ).appendTo('.someDiv');

Next, I am attempting to append code from another loop into the ul by using the ".recommendations" div's ID in the following manner...

var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');

$('<div>'+recCardName+'</div>').appendTo(recCardsList);

I have experimented with various quotation mark combinations, but have been unsuccessful in selecting the div correctly for appending new content.

Answer №1

It appears that your code is not correctly appending the newly created content to the div due to some errors:

var recCardsList = $(div).attr('id', '.recCards-'"+i+"' ul');
$('<div>'+recCardName+'</div>').appendTo(recCardsList);

The issue lies in using

.attr('id', '.recCards-'"+i+"' ul')
, which does not retrieve the list from the div but rather attempts to update its id.

When passing two arguments to .attr(), the first is the targeted attribute and the second is its new value.

To properly access the div, you should simply use $('#recCards-'+i+' ul') in your loop to target the specific lists. Your revised code should look like this:

var recCardsList = $('#recCards-'+i+' ul');
$('<div>'+recCardName+'</div>').appendTo(recCardsList);

Using $("#someId") retrieves an element with the id="someId" from the page.

Answer №2

Here's a suggestion:

Let's test out this code snippet:

var recommendedCardsList = $(element).attr('id', '.recommendedCards-'+index+' ul');

Answer №3

Given the circumstance that the variable i remains within the function's scope, the proposed solution looks like this

'recCards-'+i+' ul'

This approach should work flawlessly, as suggested in the comment. It is recommended to verify the value of variable i using console.log() or alert() because there is a possibility that i could be null based on the provided information.

If both variables are contained within the same function, you might find it helpful to refer to the following post for combining the two loops with appendTo() and append()

jQuery append inside appended element

Answer №4

Getting the list that way is unlikely. Give this a shot:

let recommendedCardsList = $('#recommendedCards-' + i + ' ul');

Additionally, it's not correct to add a <div> to a <ul>. Instead, use <li>:

$('<li>'+recommendedCardName+'</li>').appendTo(recommendedCardsList);

Answer №5

Give this a shot, employ mask and substitute with I,

let strReccards = ".recommCards-INDEX ul";
let recCardsList = $(div).attr('id', recCardIndex.replace("INDEX",I));
$('<div>'+recCardName+'</div>').appendTo(recCardsList);

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

Is HTML5 capable of supporting a multi-file uploader system in browsers?

Can you tell me which web browsers currently support the ability to select multiple files in an upload form, as introduced in the HTML5 spec? And does Adobe AIR also support this feature? As a bonus question, I'm curious if there are any JavaScript l ...

Using Vue component with v-model and custom input handler

I'm currently working on creating a wrapper component for an <input/> element in Vue.js. Here is the component code: <template> <div> <input v-bind="$attrs" :value="value" @input="input" /> ... </div> <te ...

Arranging a list based on the child property in a React component

Within my application, I have an array mapped to a map that generates a div with a data-date attribute as shown below: It's worth noting that the array cannot be sorted here since there are no dates available for comparison, only the element ID cons ...

Securing multiple routes in AngularJS using resolve for authentication

How can I authenticate users for all routes in my application without having to specify it individually? Is there a global way to handle authentication for all routes, so that I don't have to include the following code on each $routeProvider.when() c ...

Tips for incorporating dynamic content into React Material UI expansion panels while maintaining the ability to have only one tab active at a time

I'm working on a project using WebGL and React where I generate a list of users from mock data upon clicking. To display this content in an accordion format, I decided to use Material UI's expansion panel due to my positive past experience with ...

Ways to optimize memory usage and eliminate Vue reactivity

I've encountered an issue where Vue's observer and reactive components are using up a significant amount of memory during runtime. You can see an example of this in the Memory allocation on DevTools. Is there a way to detach observables and preve ...

Transform pixel padding into percentage ratios

I've been searching through various discussions to find a solution, but none of them seem to fit my particular scenario. My issue involves a hyperlink with absolute positioning inside a div with relative positioning. The padding and margins are curre ...

How can we ensure successful validation using Jquery?

I'm currently working on a basic form that includes text fields. Whenever these text fields are modified, an Ajax function is called to save the changes. However, I am facing a challenge in validating these fields using jQuery before the change even ...

Fetching Data from DataTable using AJAX in Codeigniter

I am currently developing an application using CodeIgniter. Below is the code: Controller: public function index(){ $data = array( 'record' => $this->Parameter_model->get_parameter('tbl_parameter') ); ...

Instructions for creating scrollable MaterializeCSS tabs when there are too many tabs to fit within the width of the container without scrolling

Here is an example code (SSCCE) that showcases the issue I am facing. The MaterializeCSS frontend framework documentation states: Scrollable Tabs Tabs automatically become scrollable Source However, when I attempt to use more tabs than can fit on the ...

Evaluating CSS Specificity

Is there a recommended approach for automatically testing css selectors? I am in the process of developing a SCSS framework and I want to integrate automated tests. Specifically, I aim to verify that the css selectors are functioning correctly. For examp ...

The script fails to function properly when it is accessed from a different webpage

I have been working on a website using JQuery and JQuery Mobile. As I test the pages one by one, I created a page where users can input data and get autocomplete suggestions from a PHP/MySQL database. The functionality works perfectly as intended. However ...

When attempting to upload a file using Form, it only allows for a single upload of that file and will not work when attempting to upload the same file again

After selecting a file from the file chooser and uploading it, I encounter an issue when attempting to submit the form with the same file again. The submission doesn't seem to trigger any action. If I select a file, upload it, then choose the same fi ...

Triggering this function when clicked

I am trying to figure out a way to trigger this code onClick instead of automatically. Can anyone help me with this question? Below is the JavaScript code snippet: $("input[type=radio],button").each(function () { var outputName = $(this).attr("d ...

As we iterate through each individual array within the multi-dimensional array

I'm currently working on an application using node.js, Express, and JS/Jquery. One issue I've encountered is with appending elements to a webpage based on the number of arrays contained in a MD array. Essentially, I only want to append unique e ...

performing functions concurrently within angularjs

I am currently utilizing angularjs 1.0 within my application. There is a dropdown on my cshtml page <select tabindex="2" id="Employee" ng-model="models.SelectedEmployee" ng-change="changeEmployee()" disabled="disabled" class="Answer" size="6"> < ...

exploring for a keyword on the primary Amazon platform (analyzing)

Hey everyone, I noticed that Amazon's main search bar code looks like this: <input type="submit" class="nav-input" value="Go" tabindex="7"> I'm considering creating a function that will locate this tag on amazon.co.uk and perform a search ...

Disable button with Checkbox Javascript functionality

In my PHP code, I have an array of users that I pass to the view (in Laravel) and use a foreach loop to display all users in a table. Everything is working fine so far. However, I want to make a "send" button visible when a checkbox is clicked, instead of ...

Customizing Bootstrap SCSS variables by substituting them with different Bootstrap variables

What is the most effective way to customize variables? I have found that following this specific order yields the best results: @import "bootstrap/_functions.scss"; $primary: red; @import "bootstrap/_variables.scss"; @import "bo ...

Developed a basic HTML form using PHP, however encountering issue where email is not being posted and instead opening a blank page

After creating HTML and PHP documents, I encountered an issue where upon submitting the form, I ended up with a blank page and didn't receive the expected email containing the form information. As someone relatively new to this, I would greatly apprec ...