6

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?

12
  • why do you want to stringify an object? What is the purpose? You should be storing watever you need in a json object and stringify that instead right? Commented Apr 15, 2014 at 1:39
  • 2
    Why oh why would you want to store a jQuery selection set of DOM elements or make it portable in the first place? What is in those ps? Commented Apr 15, 2014 at 1:39
  • What is the actual context for the question? It is hard to see how passing the results of a jQuery selector would ever need to be passed in a message. Unless you just need the HTML, in which case wouldn't $('p').html() be sufficient? Commented Apr 15, 2014 at 1:39
  • 1
    @jonS90 how about using the ID of the element? (or setting a UID if there is none) Commented Apr 15, 2014 at 2:05
  • 1
    @jonS90 if (!$('foo').attr('id')) { $('foo').attr('id', 'uid-' + Math.random()); } Commented Apr 15, 2014 at 2:08

1 Answer 1

9

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)

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

3 Comments

If he needs the p tag it may be better to call outerHMTL on it to capture the p tag itself.
@izuriel: Yes, that would also work for a single element. I got the feeling that he might actually have multiple though, and in that case adding them to a dummy element and using html() seems like the easiest way to get a HTML string out of them.
The HTML alone won't allow me to reconstruct the jQuery object. I think the representation should have a unique ID or Class (from which I can reconstruct the jQuery object), and additionally any components I will need, such as .html() and .css() stuff. This has been a huge help!

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.