Javascript Error: Cannot Convert Object to Primitive Value
Asked Answered
P

4

15

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?

Plasmodium answered 12/7, 2011 at 15:59 Comment(3)
var propDat = prop + ' = ' + propVal;Plasmodium
Same error if I phrase it as: var propDat = prop + ' = ' + ct[prop]; and ditch propVal.Plasmodium
I'm trying to iterate through the property of the element in question. In this case, it's an <a> element, but I'll eventually be using this for divs, etc.Plasmodium
A
9

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.

Abroad answered 12/7, 2011 at 16:13 Comment(1)
Thanks. I was able to add a condition to check for string values and act on that. This is sufficient for what I'm doing with this snippet.Plasmodium
S
5

If the object in question is json, you can call JSON.stringify(thingThatIsJson) which will return a String. .toString() does not work on json.

This is a message to those of you dealing with something like req.body which will work in console.log() which is rather confusing since it may not otherwise behave like a String (like when you're trying to add it to another String).

Saree answered 25/5, 2017 at 15:28 Comment(0)
O
2

(The OP:)

Just wanted to post the updated snippet for anyone who stumbles onto this post...

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)) {
            var propVal = ct[prop];
            props += prop + ' (' + typeof(prop) + ')' + ' = ';
            if (typeof(ct[prop]) == 'string') {
                propVal += ct[prop];
            } else {
                if (propVal != null && propVal.toString) {
                    props += propVal.toString();
                } else {}
            }
            props += '<br/>';
        }
    }
    rslt.innerHTML = props;
}
Oleaginous answered 1/12, 2016 at 12:1 Comment(0)
R
1

The problem lies with the propVal part of your code. Since that may not be converted into a string.

Rubbico answered 12/7, 2011 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.