Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you stringify a jQuery object?

The line JSON.stringify( $("p") ); causes an error:

InvalidStateError: Failed to read the 'selectionDirection' property from 'HTMLInputElement': The input element's type ('button') does not support selection.

(I'm using Google Chrome 34)

Why?

How else should I make $("p") more portable so I can store it or pass it in a message?

like image 920
jonS90 Avatar asked Apr 15 '14 01:04

jonS90


People also ask

Can we Stringify function in JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

Can JSON Stringify throw?

stringify() throws an error when it detects a cyclical object. In other words, if an object obj has a property whose value is obj , JSON. stringify() will throw an error.

Does JSON Stringify remove functions?

stringify() method not only stringifies an object but also removes any function if found inside that object.

What is the return type of JSON Stringify?

Return Value: It returns a string for a given value. Example: The below is the example of the JSON stringify() Method.


1 Answers

There's a ton of state (attributes, event handlers, the code related to those, internal state, ...) involved in an HTML element. It just doesn't make sense to serialize all of that into JSON.

If you want to get some kind of representation of the element in JSON, you could for instance use .html() to get a HTML string representing the element. Or come up with a format that encodes, for instance, tag names, attributes and text only. You could have to implement that by hand though (or find a library - "html to json" could be a good keyword)

like image 124
Matti Virkkunen Avatar answered Sep 28 '22 18:09

Matti Virkkunen