Parsing HTML Response in jQuery
My page needs to grab a specific div from another page to display within a div on the current page. It's a perfect job for $.load
, except that the HTML source I'm pulling from is not necessarily well-formed, and seems to have occasional tag errors, and IE just plain won't use it in that case. So I've changed it to a $.get
to grab the HTML source of the page as a string. Passing it to $
to parse it as a DOM has the same problem in IE as $.load
, so I can't do that. I need a way to parse the HTML string to find the contents of my div#information
, but not the rest of the page after its </div>
. (PS My div#information
contains various other div
's and elements.)
EDIT: Also if anyone 开发者_Python百科has a fix for jQuery's $.load
not being able to parse response HTML in IE, I'd love to hear that too.
If the resource you are trying to load is under your control, your implementation spec is poorly optimized. You don't want to ask your server for an entire page of content when you only really need a small piece of that content.
What you'll want to do is isolate the content you want, and have the server return only what you need.
As a side note, since you are aware that you have malformed HTML, you should probably bite the bullet and validate your markup. That will save you some trouble (like this) in the future.
Finally, if you truly cannot optimize this process, my guess is that you are creating an inconsistency because some element in the parsed HTML has the same ID as an element on your current page. Identical ID's are invalid and lead to many cross-browser JavaScript problems.
Strictly with strings you could use a regular expression to find the id="information"
tag contents. Never parse it as html.
I'd try the $.load
parameter that accepts a html selector as well
$('#results').load('/MySite/Url #Information');
精彩评论