Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
925 views
in Technique[技术] by (71.8m points)

jquery - Find element at HTML string

Let's suppose I have

var testHTML = "<div id='demo_div'></div>";

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

and with:

 var found = $(testHTML).find("div");

Both without luck. I have empty found variable. What am I do wrong?

P.S. Yes I know I can have direct access to my div with

$("#demo_div") 

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.

UPDATE: Even if I have not root div element like here:

var testHTML = "<html><div id='demo_div'></div></html>";

I can't use find for navigating div element.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...