I am not quite sure, and haven't been able to find anything.
Using stringByEvaluatingJavascriptFromString:, I have been able to manipulate javascript in my page from objective-c. However, I now want to populate form fields by passing raw xml data from the iOS UIWebView into the html file (which is local to the app), and then using the parsed data.
Looking over the W3C document, it seems I need to do something like:
parser = new DOMParser();
xmlString = parser.parseFromString(txt, "text/xml");
Which should return a DOM object from the XML (which here is represented by the string txt). I should then be able to access the properties of this DOM object from
xmlString.getElementsByTagName("from")[0].childNodes[0].nodeValue;
Assuming we have an XML node such as:
<from>Sender</from>
However, this doesn't seem to work. Setting that nodeValue into a string and returning it returns nil. Likewise, form fields are not populated.
My question, then, is whether the embedded browser in an app can utilize the DOM Parser - and if it can, what syntax I might use to access values from it?
Solved, unfortunately very fast. It seems that when setting form fields you need to specify VALUE instead of innerhtml.
so I did:
document.getElementById("FIELDID").value =
xmlString.getElementsByTagName("from")[0].childNodes[0].nodeValue;
Also, I had the parameters passed to the DOM parser wrong - it is "text/xml" for the second parameter.
Related
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?
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)
I need to access general information from my site using javascript. So far, I have the following options:
Using an html element :<input type="hidden" value="MyValue"/>
Using a custom attribute in an existing html element : <div id="HtmlElement" myattr="MyValue"></div> and then access it using document.getElementById("HtmlElement").getAttribute("myattr")
Using a data attribute in an existing html element: <div id="HtmlElement" data-myattr="MyValue"></div> and then access it using jQuery("#HtmlElement").data("myattr")
I was wondering what are the benefits of using either option.
I'm not a fan of using hidden inputs because I don't like the idea of having a loose html element that contains information. But since I need it to display general information, not information related to an existing html element in the page, it doesn't seem so bad.
On the other side, I'm not a fan of abusing the use of an external library but in my case I'm allready loading jQuery in my site, so it's not as if i was loading an entire library just for this.
And finally, even dough performance is allways an issue, in my case it's not gonna make much difference if it's the fastest solution.
I would go with data attributes because that's what they are for and modern browsers have a native api for accessing them, while still allowing non-modern browsers to access them as custom attributes.
given this html:
<div data-foo="bar"></div>
// modern browser:
foo = document.getElementByID("myelementid").dataset.foo;
// older browser:
foo = document.getElementByID("myelementid").getAttribute("data-foo");
// jQuery (all browsers)
foo = $("#myelementid").data("foo");
Note if your data attribute is data-foo-bar, the key in dataset and .data will be fooBar
As sdespont mentions, the data should be relevant to the element you are storing it on.
Update:
It's also important to note that you can also get the value of a data attribute using the .attr method, however there is a pretty important difference between the two. Getting a data attribute's value with .data will attempt to parse the value of the attribute into the correct javascript type, for example, if it can be converted to an int, it will be converted to an int. If it can be converted into an object or an array, it will be converted to an object or an array. If you instead used .attr(), you can be sure that you will always have a string.
Probably also worth mentioning that using .attr() should be prefered over .data() unless you specifically need the features given by .data() due to the fact that by using .data(), a data cache will be created for that element and it's data, which isn't needed unless you actually intend to use .data() multiple times or need the extra features provided by .data()
I have been using a DOMParser object to parse a text string to an XML tree. However it is not available in the context of a Web Worker (and neither is, of course, document.ELEMENT_NODE or the various other constants that would be needed). Is there any other way to do that?
Please note that I do not want to manipulate the DOM of the current page. The XML file won't contain HTML elements or anything of the sort. In fact, I do not want to touch the document object at all. I simply want to provide a text string like the following:
<car color="blue"><driver/></car>
...and get back a suitable tree structure and a way to traverse it. I also do not care about schema validation or anything fancy. I know about XML for <SCRIPT>, which many may find useful (hence I'm linking to it here), however its licensing is not really suitable for me. I'm not sure if jQuery includes an XML parser (I'm fairly new to this stuff), but even if it does (and it is usable inside a Worker), I would not include an extra ~50K lines of code just for this function.
I suppose I could write a simple XML parser in JavaScript, I'm just wondering if I'm missing a quicker option.
according to the spec
The DOM APIs (Node objects, Document objects, etc) are not available to workers in this version of this specification.
I guess thats why DOMParser is not availlable, but I don't really understand why that decision was made. (fetching and processing an XML document in a WebWorker does not seems unreasonnable)
but you can import other tools available: a "Cross Platform XML Parsing in JavaScript"
At this point I like to share my parser: https://github.com/tobiasnickel/tXml
with its tXml() method you can parse a string into an object and it takes only 0.5kb minified + gzipped
Is there a way to get a response from the typical ajax function so that it can be dissected with getElements? I've tried query.responseText.getElementById but it works just as bad as it looks. You should be able to tell what I'm trying to achieve by seeing that snippet, though. I just need to get elements from an ajax response the same way as I would a normal DOM object.
Also, please do not suggest using jQuery. I use it when I have a lot of script and can use a lot of its functions, but in this case I only have a short script and a library 70x the size of it would seem like a waste.
Parsing an SVG or HTML document
parser = new DOMParser();
doc = parser.parseFromString(stringContainingHTMLSource, "text/html");
doc will be a valid html document.
Well you could have a hidden div on your page and set it's innerHTML to the Ajax response you receive. You could then call div.getElementById(), since it is then just another DOM object.
Refer to this article: Parsing XML response in Ajax
In this case I am using responseXML. You can make use of getElementsByTagName and other getElement*() methods to get your data.
If your response is TEXT, I've seen ppl use ...xhr.responseText.spit('html>...body>...div id="yourTargetsParent">')[1].split('/div>.../body>.../html>')[0]; //just split the string up however!
Another way is to use iframe.contentWindow.document.body... (or contentDocument for some browsers)... just hide the iframe ya know.
Obviously, if you have control over the target that totally changes things (and this post probably wouldn't be here), but I've also seen some mean work arounds with the target's use of scripting its host dom, localStorage, splits/joins, webSQLDatabases, ...for string manipulation.
Honestly, I used to use a hidden div(thank you asleepysamurai!), but I thought I came across a more getElementById/jQuery.load type way. ..I'll post back if I find it...
Is it possible to check if loaded with xmlDoc.loadXML(xmlData); xml string is invalid? For example if there is missed closing bracket or a tag.
If you pass a string to loadXML that isn't a well-formed XML document, the document object will be empty (no childNodes) and xmlDoc.parseError.errorCode will be set to something other than 0. xmlDoc.parseError.reason will give you a user-readable error message.
If you want to test a snippet and not a full document, wrap it in <x>...</x> tags so that the parser will only see one root element.
(There are a few reasons that MSXML might fail to parse a document other than it being non-well-formed. For example an external DTD subset or entity might not be network-reachable, or the DTD might use features MSXML doesn't support. You can't use MSXML to parse XHTML documents with their DTD for this reason. But if DTD-cruft isn't involved, a parser failure means the input wasn't well-formed.)
All info about parse errors is hidden in "xmlDoc.parseError"