0

This should be really simple, but for some reason I just can't get it work. I have an array of class names that might exist on the page. I loop through this array and check if that class exists, if it does, I add that object to another array.

jQuery:

var class_list = ['class1', 'class2', 'class3'];
var classes = {};

$(function(){   
    if( class_exists() ){
        console.log('Classes: '+JSON.stringify(classes));
    }
});

function class_exists(){
    var exists = false;
    for( var i=0; i<class_list.length; i++ ){

        //check if the class exists:
        if( $('.'+class_list[i])[0] ){
            classes[class_list[i]] = $('.'+class_list[i]); 
            exists = true;
        }
    }
    return exists;
}

The output of this is Uncaught TypeError: Converting circular structure to JSON. I expected to see something like {'class1': [object Object], 'class2': [object Object]}. This should be so simple, where am I going wrong?

MP_Webby
  • 916
  • 1
  • 11
  • 35
  • 1
    You are getting `Uncaught TypeError: Converting circular structure to JSON` because you are trying to stringify a jQuery object which contains DOM node references. DOM nodes are not serializable because they contain circular references (e.g. `parentNode.children[0].parentNode`) – circusbred Feb 26 '15 at 19:45
  • possible duplicate of [How do I solve this Javascript error when converting JSON to string?](http://stackoverflow.com/questions/4954242/how-do-i-solve-this-javascript-error-when-converting-json-to-string) – theonlygusti Feb 26 '15 at 19:49

1 Answers1

1

It's all because of this line:

console.log('Classes: '+JSON.stringify(classes));

Since your using the browser console, just use

console.log('Classes: ', classes);

My browser (chrome), at least, has support for rendering objects. I you're using nodejs, I used util.inspect to overcome the same problem.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119