将整个HTML文档从字符串解析为jQuery [英] Parse entire HTML document from string into 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屋!