Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hasClass 'is not a function'

I want to check with jQuery which li element from a list of li elements is the active one (they represent a menu, and I want to check which menu item is currently active).

So, I store all the li items in a variable, myElements. Then I ask the length of myElements, and apply some style changes to them, up to here everything works. Apparently this way my variable myElements is a Nodelist, not an array, so I declare another variable; myElements_array, which contains the same elements as myElements and is an array (also tested and it works).

Then I try to check which of the elements from myElements_array has the 'current-menu-item' class, but it doesn't work and the google chrome console says there's an error: 'Uncaught TypeError: myElements_array[j].hasClass is not a function'. Does anyone have an idea what the reason might be?

<script type='text/javascript'>
var myElements = jQuery("#navbar > ul > li");
var count = myElements.length;

for (var i = 0; i < myElements.length; i++) {
myElements[i].style.width = (100/count)+'%';
}

var myElements_array = [];
for(var i = myElements.length; i--; myElements_array.unshift(myElements[i]));

var j = 0;
while (! myElements_array[j].hasClass('current-menu-parent') ) {
j++;
}
document.write(j);
</script>
like image 728
rubencart Avatar asked Jun 03 '15 21:06

rubencart


1 Answers

Problem is the index you are pulling from the array is a DOM node when you use bracket notation and it is not a jQuery object. DOM does not have hasClass.

You can either store the jQuery version or change it to jQuery

while (! $(myElements_array[j]).hasClass('current-menu-parent') ) {

or use classList contains

while (! myElements_array[j].classList.contains('current-menu-parent') ) {

or use eq() instead of referencing the DOM

while (! myElements_array.eq(j).hasClass('current-menu-parent') ) {
like image 50
epascarello Avatar answered Sep 29 '22 03:09

epascarello