20

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.

Michael Z
  • 3,883
  • 10
  • 43
  • 57

2 Answers2

51

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.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
  • 1
    Yes I have more complex HTML and my div is not the root of it. But _find_ is not work there! – Michael Z Nov 16 '12 at 09:07
  • 3
    @MichaelZ - Then your problem is most likely elsewhere. If the element you are looking for is at the root of the collection, use `.filter()`, if it's not, use `.find()`. See [this example](http://jsfiddle.net/jamesallardice/CWnvu/1/). – James Allardice Nov 16 '12 at 09:11
  • 2
    @MichaelZ - jQuery strips out the `` element, so your `div` is actually the root. – James Allardice Nov 16 '12 at 09:30
1

You could use the .search() function of the javascript itself.

testHTML.search('demo_div')>-1
Manoj De Mel
  • 927
  • 9
  • 16