-1

I am using the following Jquery Code

(function ($) {
    $('.afc_close_content').click(function() {          
        var afc_content_id = $(this).closest('div').attr('id');
        $('#'+afc_content_id).hide();
    });
})(jQuery);

I have change it JavaScript

(function () {
    document.getElementByClassName("afc_close_content").click(function() {          
        let afc_content_id = this.closest('div').attr('id');
        $('#'+afc_content_id).style.display = "none";
    });
});

But the above code does not work

Where am I wrong?

URL: https://www.wordpress4.guru99.com/what-is-sap.html

StuiterSlurf
  • 2,464
  • 4
  • 34
  • 55
Tushar Korat
  • 591
  • 2
  • 7
  • 21
  • See also [What do querySelectorAll and getElementsBy\* methods return?](/q/10693845/4642212). Neither an `HTMLCollection` nor a `NodeList` has a `click` method. This reminds me of the article [jQuery considered harmful](//lea.verou.me/2015/04/jquery-considered-harmful/). – Sebastian Simon Aug 31 '21 at 16:00
  • 1
    Use [event delegation](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](//developer.mozilla.org/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). – Sebastian Simon Aug 31 '21 at 16:00
  • 2
    You have at least four distinct problems here (not counting the bit where you're still calling the jQuery function). Focus on one at a time. – Quentin Aug 31 '21 at 16:01
  • Please see [something in my website doesn't work - can I just paste a link](https://meta.stackoverflow.com/questions/254428/something-in-my-web-site-or-project-doesnt-work-can-i-just-paste-a-link-to-it) – freedomn-m Aug 31 '21 at 16:10

1 Answers1

-1
  1. You can loop over the elements.
  2. Use addEventListener instead of the jQuery .click method.
  3. Use document.querySelectorAll, document.querySelector, or document.getElementById instead of the jQuery function.
(function() {
    document.querySelectorAll(".afc_close_content").forEach(el => 
      el.addEventListener('click', function() {
        let afc_content_id = this.closest('div').id;
        document.getElementById(afc_content_id).style.display = 'none';
      })
    );
});
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • To point 1: no, you don’t _need_ to loop over the elements. You can use the DOM event propagation model to your advantage instead. – Sebastian Simon Aug 31 '21 at 16:11
  • @SebastianSimon I agree that event delegation can be used instead, but this is just a direct rewriting of the jQuery code in the original post. – Unmitigated Aug 31 '21 at 16:33