Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find element at HTML string

Tags:

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.

like image 629
Michael Z Avatar asked Nov 16 '12 09:11

Michael Z


People also ask

How do you identify an element in HTML?

3. Getting HTML elements by Id: The Id selectors are used to uniquely identify an HTML element in an HTML document. In General, An HTML element is provided with a unique id, and then users can use the getElementById() method to access the particular element by passing that id value into the method.

How do you find the text of an element?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.


2 Answers

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.

like image 104
James Allardice Avatar answered Oct 21 '22 01:10

James Allardice


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

testHTML.search('demo_div')>-1
like image 34
Manoj De Mel Avatar answered Oct 21 '22 03:10

Manoj De Mel