将整个HTML文档从字符串解析为jQuery [英] Parse entire HTML document from string into jQuery

查看:95
本文介绍了将整个HTML文档从字符串解析为jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过$.get调用获取的文档,它是一个很大的HTML文档.我需要使用jQuery从中获取元素.

I have a document fetched by a $.get call, it's a big bloated HTML document. I need to use jQuery to grab an element from it.

我正在尝试这个(在咖啡脚本中):

I'm trying this (in coffeescript):

$.get url, (data) ->
  title = $(data).find('title').text()

这不起作用.在浏览器控制台中,我将其缩减为$(document.documentElement.outerHTML).find('title'),其中document.documentElement.outerHTML提供了文档的字符串.

This doesn't work. In browser console I've whittled this down to $(document.documentElement.outerHTML).find('title') where document.documentElement.outerHTML gives a string of the document.

我尝试 jQuery.parseHTML ,结果相同.

推荐答案

之所以不起作用,是因为jQuery期望DOM节点找到"title"标签.如您所述,您需要先解析html文本.

The reason why it does not work is because jQuery expects a DOM node to find the 'title' tags. As you noted, you need to parse the html text first.

此处

From here and here, the solution is to parse the string and append it into a temporal div (or other element):

var tempDom = $('<div></div>').append($.parseHTML(str));

然后,您可以操纵tempDom来查找元素.

Then, you can manipulate tempDom to find elements.

工作演示: http://codepen.io/anon/pen /wKwLMP

这篇关于将整个HTML文档从字符串解析为jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆