在HTML字符串中查找元素 [英] Find element at HTML string
问题描述
假设我有
var testHTML = "<div id='demo_div'></div>";
我希望得到上面的 div 作为JQuery对象来处理它。我试图找到它:
I want to get above div as JQuery object to manipulate with it. I try to find it with:
var found = $(testHTML).find("#demo_div");
与:
var found = $(testHTML).find("div");
没有运气。我找到空 变量。我做错了什么?
Both without luck. I have empty found variable. What am I do wrong?
PS 是的,我知道我可以直接访问我的 div
P.S. Yes I know I can have direct access to my div with
$("#demo_div")
但我不能在我的情况下 - 我需要从纯HTML中获取它将被分配到一些变量,就像我的例子中的 testHTML var。
but I can't do it in my case - I need to get it from plain HTML that will be assigned to some variable just like in my example with testHTML var.
更新:
即使我没有root div 元素,如下所示:
var testHTML = "<html><div id='demo_div'></div></html>";
我无法使用查找导航 div
I can't use find for navigating div element.
推荐答案
问题是您的 div
是收集中的根元素,因此您需要使用 .filter()
而不是 .find()
(仅查看后代元素):
The problem is that your div
is the root element in the collection, so you need to use .filter()
instead of .find()
(which only looks at descendant elements):
var found = $(testHTML).filter("#demo_div");
我假设你的实际HTML字符串比问题的复杂,否则你不需要执行 $(testHTML)
以外的其他任何东西,您将拥有一个包含该单个元素的jQuery对象。
I'm assuming your actual HTML string is more complex than the one in the question, otherwise you don't need to do anything other than $(testHTML)
and you will have a jQuery object containing that single element.
这篇关于在HTML字符串中查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!