Uncaught TypeError: .slideToggle is not a function

I have jquery in another file located on the same map, I use this code below to activate the function .slideToggle. However, it does not work, why?

jQuery(document).ready(function ($) {

    // get li items
    var ul = document.getElementById("menu-footermenu");
    var items = ul.getElementsByTagName("li");

    // display 5 li items, hide others
    for (var i = 0; i < items.length; ++i) {
        if (i > 5) {
            items[i].style.display = "none"
        }
    }

    // when clicking on more catogories button, display all items
    $('#morecat').click(function () {
        for (var i = 0; i < items.length; ++i) {
            if (i > 5) {
                items[i].slideToggle();
                document.getElementById("morecat").style.display = "none";
            }
        }
    });
});

I get an error message:

Uncaught TypeError: .slideToggle is not a function

+4
source share
2 answers

The problem is that the contents itemsare Element objects, not jQuery objects, so the function is slideToggle()not available.

To fix this, you need to convert them:

$(items[i]).slideToggle();

Alternatively, you can convert all the logic to use jQuery, instead of having the pretty odd half / half solution you have now:

jQuery(function ($) {
  var $ul = $("#menu-footermenu");
  var $items = $("li");
  $items.filter(':gt(4)').hide();

  $('#morecat').click(function () {
    $items.filter(':gt(4)').slideToggle();
    $(this).hide();
  });
});
+2

, slim jquery, , .

+3

Source: https://habr.com/ru/post/1684728/


All Articles