'How to trigger onclick div using javascript

I want to trigger onclick of my div using click event in javascript. But I can be avble to trigger the onclick using jquery. Below is my code.

html += '<div id="add_redirect" class="row pl_filter_value margin-bottom-md ' + applied_class + '"onclick="applyFilter( \'' + filter.name + '\', \'category\', \'true\');"><div class="col-xs-12">In Stock Only' + applied_cross+ </div></div>';

$("document").ready(function() {
        setTimeout(function() {
            $("#add_redirect").trigger('click');
        },1);
    });

if I trigger by using document.getElementById('add_redirect').click(); the error is telling as Cannot read properties of null (reading 'click') .Thanks in advance



Solution 1:[1]

Use addEventListener https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event

html += `
  <div id="add_redirect" class="row pl_filter_value margin-bottom-md + ' ' + ${applied_class}">
    <div class="col-xs-12">In Stock Only + ${applied_cross} </div>
  </div>
`;

$("document").ready(function() {
  const el = document.getElementById("add_redirect");
  el.addEventListener("click", () => {
    // handle onclick here
  });

  setTimeout(function() {
    el.click();
  }, 1);
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1