Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Error: Cannot Convert Object to Primitive Value

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?

like image 666
Eric Avatar asked Jul 12 '11 15:07

Eric


People also ask

How to convert object to primitive in JavaScript?

With the help of the Symbol. toPrimitive property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument hint , which specifies the preferred type of the result primitive value. The hint argument can be one of "number" , "string" , and "default" .

How do you turn a string into an object in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.


1 Answers

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.

like image 51
Itay Moav -Malimovka Avatar answered Oct 31 '22 03:10

Itay Moav -Malimovka