Javascript error: cannot convert object to primitive value

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

It puzzles me. Any ideas?

+4
source share
4 answers

Not all properties of an HTML element are primitives. e.g. parent, childs etc. are also HTML elements. You cannot just use them as strings or numbers.
You need to add a condition and use this property accordingly.

+3
source

(OP :)

I just want to publish an updated snippet for everyone who came across 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; } 
+1
source

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

This message is for those of you who are dealing with something like req.body that will work in console.log() , which is quite confusing, since it cannot behave differently from String (for example, when you trying to add it to another String).

+1
source

The problem is the propVal part of your code. Since it cannot be converted to a string.

0
source

All Articles