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?

3
  • var propDat = prop + ' = ' + propVal; Commented Jul 12, 2011 at 16:12
  • Same error if I phrase it as: var propDat = prop + ' = ' + ct[prop]; and ditch propVal. Commented Jul 12, 2011 at 16:12
  • 1
    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. Commented Jul 12, 2011 at 16:14

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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;
}

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.