How to debug this error in JQuery=> Uncaught TypeError: Cannot read property 'toString' of undefined

I write the Jquery code for getting all class names of a div when the page scroll.
This is the Jquery code–

$(window).scroll(function () {
		if ($(window).scrollTop() > stickySidebar) {$('.nav-container').addClass('f-nav');}
		else {$('.nav-container').removeClass('f-nav');}
        //Get list of CSS class names
        var classNames = $("#view").attr("class").toString().split(' ');
        $.each(classNames, function (index, item) {
            if (item === 'show') {
				$(window).scroll(function() {
					if ($(window).scrollTop() > 1180) {$('.nav-container').addClass('f-nav');}
					else {$('.nav-container').removeClass('f-nav');}
				});
			}else{
				$(window).scroll(function() {
					if ($(window).scrollTop() > stickySidebar) {$('.nav-container').addClass('f-nav');}
					else {$('.nav-container').removeClass('f-nav');}
				});
			}
        });
    });

This code is working fine but the problem is when I do inspect element then it shows error "
Uncaught TypeError: Cannot read property ‘toString’ of undefined
".
So please tell me that how I remove this error.
Thank you.

This means that #view either doesn’t exist or it doesn’t have any classes; you’d need to check this before attempting to split() them (note that toString() is redundant anyway). Like e.g.

var classNames = $('#view').attr('class');
var classArray = classNames ? classNames.split(' ') : [];

BTW, you’'re adding a new scroll event listener for each class each time you scroll… this can’t be right. I think you can simply remove those inner scroll handlers.

.attr() method return the string value by default, so you don’t have to use additional toString()

so what I do for this?

Get rid of the toString() method maybe ?

I don’t understand, what you want to say?
can you please give any example or do modification in js which is I write above.

This piece of code

var classNames = $("#view").attr("class").toString().split(' ');

As you can see you are attaching the .toString() method on .attr() method and it’s reduntant, because .attr() method return the string value, so basically you are trying convert string to string.

So try this

var classNames = $("#view").attr("class").split(' ');

I already try this => var classNames = $(“#view”).attr(“class”).split(’ ');
but when I use this then it shows this error => Uncaught TypeError: Cannot read property ‘split’ of undefined

Then take a look on @m3g4p0p suggestion.

ok thanks

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.