Solution 1 :

In regard to appending the span, an ID must must be selected with a “#”, but it looks like it is never modified after being passed into the function. Try rewriting the selector as a template literal:

$(`#${ID}`).append

or string concatenation:

$("#" + ID).append

Problem :

I’m trying to create a button that when clicked creates a list item and adds it to an existing list. I’m trying to achieve this by using JQuery. I’d very much like to use bootstrap on the list item and append a <span> tag to each list item also with a bootstrap class. I’m having trouble with appending the span tag and with assigning an id to each list item for later use.

this is what I got so far:

Button:

<button onclick="AddItem('@Dish.DishName','@Dish.Price',@Dish.DishId)">@Dish.DishName</button>

JQuery function:

function AddItem(Name, Price, ID) {
            $(".order").append(
                $('<li/>').attr("id", ID).addClass("list-group-item").text(Name/* + "          " + Price*/));
            $(ID).append(
                $('<span/>').addClass("badge").text(Price)

            );
        }

Would appreciate any help or advice

TIA

Comments

Comment posted by swolfy

Thanx Pavlos, should i have modified it and if so then how? also if i wanted later on to use queryselectorAll on a couple of list itemes with the same id how would i go about doing that?

Comment posted by Pavlos Karalis

As shown in my above answer, adding the “#” via a template literal or string concatenation. If querySelectorAll is called within the function, you would again add the “#” via the above methods (though elements technically shouldn’t share IDs, only classes). Since querySelectorAll creates an array, you could then iterate it through a for loop to append something to each element:

Comment posted by codepen.io/PavlosKaralis/pen/dyGROZG

I created a code pen to demonstrate querySelectorAll:

By