Following a jQuery ajax call to retrieve an entire XHTML document, what is the best way to select specific elements from the resulting string? Perhaps there is a library or plugin that solves this issue?
jQuery can only select XHTML elements that exist in a string if they're normally allowed in a div in the W3C specification; therefore, I'm curious about selecting things like <title>
, <script>
, and <style>
.
According to the jQuery documentation:
http://docs.jquery.com/Core/jQuery#htmlownerDocument
The HTML string cannot contain elements that are invalid within a div, such as html, head, body, or title elements.
Therefore, since we have established that jQuery does not provide a way to do this, how would I select these elements? As an example, if you can show me how to select the remote page's title, that would be perfect!
Thanks, Pete
You can also simply temporarily wrap inside a div. You don't even need to add it to the DOM.
Just an idea - tested in FF/Safari - seems to work if you create an iframe to store the document temporarily. Of course, if you are doing this it might be smarter to just use the src property of the iframe to load the document and do whatever you want in the "onload" of it.
I had to append the iframe to the body to get it to have a .contentWindow.
Inspired from this answer, but with deferred:
And smoke it with:
LIVE DEMO (click 'Run')
How about this: Load XML from string
If you wanted to find the value of specifically named fields (i.e. the inputs in a form) something like this would find them for you:
After parsing the XML string into an
XML DOM
, I'd either usejQuery
on it directly (you can do this by providing a context to thejQUery
selector, such as$(':title', xdoc.rootElement)
or usingXPath
(works in Firefox; there are supposedly libraries for IE but I haven't had good success with them).