I've got javascript object that holds a few depths of data. One of the depths has literal dom elements attached. I need to post this object (I'm using jQuery's post func), but I get an illegal invocation because of those dom elements. Is there a quick way to remove those dom elements without having to loop through the object / array?
Asked
Active
Viewed 33 times
0
-
3No, not really. If there was, it'd have to just hide the looping/recursion in a function. – PurkkaKoodari Sep 07 '14 at 17:46
-
How do you send it? As XML? JSON? Do you actually want to send the DOM elements? – Bergi Sep 07 '14 at 17:47
-
@Bergi sending as JSON. I don't want the dom elements sen, I don't think you even can. – Michael Mikhjian Sep 07 '14 at 17:47
-
I think you can use ```.filter()```, but in the end; there will still be an internal loop – adi rohan Sep 07 '14 at 17:49
-
@adirohan filter won't work for this case. – Michael Mikhjian Sep 07 '14 at 17:52
-
yes, you are right , so ```for in``` loop would work – adi rohan Sep 07 '14 at 17:56
1 Answers
1
Yes, there is. When serializing the Objects to JSON, you can use a replacer
predicate to remove or modify arbitrary data. In your case it would look like this:
$.ajax({
url: "…",
data: JSON.stringify(data, function(p,o) {
if (o instanceof HTMLElement) return null;
return o;
}),
…
});
For more thorough ways of detecting DOM elements see JavaScript isDOM -- How do you check if a JavaScript Object is a DOM Object?.
-
I see what you did there! This doesn't work though, it returns an empty string. – Michael Mikhjian Sep 07 '14 at 18:04
-
Right, I forgot the `propertyName` argument of the replacer. Works now :-) – Bergi Sep 07 '14 at 18:15