简体   繁体   中英

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 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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM