Javascript Error: Cannot Convert Object to Primitive Value

Eric picture Eric · Jul 12, 2011 · Viewed 64.3k times · Source

I'm receiving this error using the following javascript code:

function tempTest(evt) {
    alert(evt.currentTarget.id);
    ct = document.getElementById(evt.currentTarget.id);
    rslt = document.getElementById('rslt');
    var props;
    for (var prop in ct) {
        if (ct.hasOwnProperty(prop)) {
            propVal = ct[prop];
            var propDat = prop + ' = ' + propVal;
            props += propDat + '<br/>';
        }
    }
    rslt.innerHTML = props;
}

This one has me puzzled. Any ideas?

Answer

Itay Moav -Malimovka picture Itay Moav -Malimovka · Jul 12, 2011

Not all the properties of a HTML element are primitives. for example, parent, childs etc are also HTML elements. You can't just use them as strings or numbers.
You need to add there a condition and use that property accordingly.