2

I am appending html code to a div using jquery. Part of that code references a div's id using a concatenated variable from a loop.

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

I'm then trying to append code from another loop into the ul by referencing the ".recommendations" div's ID like so...

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

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

I've tried every combination of quotation marks that i can think of, but nothing grabs the div correctly to append the new content

Holly Michelle
  • 95
  • 2
  • 15
  • 2
    You are putting css select as your id, `'.recCards-'"+i+"' ul'`. If you were trying to find the element it would be `$('#recCards-'+i+" ul")` – Patrick Evans Jul 07 '17 at 23:36

5 Answers5

1

Actually your code doesn't append the new created content to the div, because it has some errors:

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

By writing .attr('id', '.recCards-'"+i+"' ul') you are not getting the list from the div but, you are trying to update its id.

Actually if we pass two arguments to .attr(), the first will be the targeted attribute and the second one is its new value.

So to get the div you should just use $('#recCards-'+i+' ul') in your loop it will gets the respective lists, so your code would look like:

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

Here using $("#someId") will get the element with the id="someId" from the page.

cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

Try this:

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

Assuming that variable i is still within the scope of the function the solution stated above

'recCards-'+i+' ul'

Would definitely work, as stated in the comment check either with console.log() or alert() what variable i is there is a chance due to what was given i is null.

If they are within the same function you can also look at this post to combine the 2 loops with appendTo() and append()

jQuery append inside appended element

0

You'll hardly get the list that way. Try this:

var recCardsList = $('#recCards-' + i + ' ul');

Also it's not valid to append <div> to <ul>. It'd rather be <li>:

$('<li>'+recCardName+'</li>').appendTo(recCardsList);
Kosh
  • 16,966
  • 2
  • 19
  • 34
0

Try this, use mask and replace by i,

var strReccards = ".recCards-MYINDEX ul";
var recCardsList = $(div).attr('id', recCardIndex.replace("MYINDEX",i));
$('<div>'+recCardName+'</div>').appendTo(recCardsList);
JG73
  • 90
  • 1
  • 10