Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  148] [ 7]  / answers: 1 / hits: 24517  / 9 Years ago, wed, june 3, 2015, 12:00:00

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>

More From » jquery

 Answers
9

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') ) {

[#66340] Tuesday, June 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marinal

Total Points: 655
Total Questions: 99
Total Answers: 99

Location: Svalbard and Jan Mayen
Member since Sun, Sep 25, 2022
2 Years ago
;