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?

Eliran Malka
  • 15,821
  • 6
  • 77
  • 100
Eric
  • 2,061
  • 8
  • 28
  • 37

4 Answers4

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.

Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
  • 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. – Eric Jul 12 '11 at 16:32
4

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).

Glen Pierce
  • 4,401
  • 5
  • 31
  • 50
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;
}
Eliran Malka
  • 15,821
  • 6
  • 77
  • 100
1

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

Ankit
  • 423
  • 2
  • 12