Trigger Click on Dynamic Buttons – JS

I am creating several buttons once I read some data from a JSON file. The buttons are being create this way:

element.after('<button class="button ' + subcategoriesData.tag + '" category="' + category.tag + '" subcategory="' + subcategoriesData.tag + '">' + subcategoriesData.title + '</button>');

I want to create a click as soon as the page loads so one of these buttons is automatically selected.

I have tried to select one of the elements and trigger a .click() but still, this didn’t work. I have also tried to find the element from its parent element and trigger a .click() but still, it didn’t work.

Do you have any ideas what else I can try?

Since you are using jquery, you may want to consider using jQuery to create the element this way (then you don’t have to worry about managing the syntax:

$("<button/>").attr({
   class: "button",
   category: category.tag,
   subcategory: subcategoriesData.tag
}).appendTo("#elementID");

The appendTo method will append using any selector. You can also attach to the click event using .on(“click”, function(e) { }) within this statement as well.

Whatever solution you use to create the button, $(“.button:first”).trigger(“click”) will trigger the click event; if it’s not firing, run your selector with a .length property check and see if it’s returning 0; if it is, the selector isn’t finding the button.