2

I have an array which I want to display on a badge therefor I have appended as below

           attachmentArray.forEach((element, index) => {
                console.log(index, element.name)
                attachmentBadge.append(`
                     <div id="attachmentBadge_` + index + `" class="badge bg-navy m-1">
                        <div id="file_list_` + index + `" class="d-flex align-items-center justify-space-between">
                            <span id="file_` + index + `">` + element.name + `</span>
                            <span id="closeAttachmentBtn_` + index + `"   value='` + index + `' class="btn btn-sm text-light closeAttachment">
                                &times;
                            </span>
                        </div>
                     </div>
                `)
            });

I also have a function to trigger a console.log when i clicking on

<span id="closeAttachmentBtn_` + index + `"   value='` + index + `' class="btn btn-sm text-light closeAttachment"> &times; </span>

but when i click it isn't working.


        $("div#attachmentBadge.closeAttachment").click(function() {
            console.log('clicked')
        })

what is the correct method to access the function?

wizze mate
  • 21
  • 2
  • 2
    `$("div#attachmentBadge.closeAttachment")` only applies to elements that exist *at the time that code runs* - so when you add `.closeAttachment` button after, it doesn't have that event. You need to use *event delegation* - `$(document).on("click", ".closeAttachment", function...` – freedomn-m Nov 30 '21 at 16:44
  • Note that your selector should *probably* be (based on what's provided and some assumptions): `$("div#attachmentBadge .closeAttachment")` - note the extra `space` before `.closeAttachment` to select child elements of the parent `div#attachmentBade`. So may just be a typo. – freedomn-m Nov 30 '21 at 16:46

0 Answers0