Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find element in variable

I have:

var html_data = '<div class="div1">something</div><div id="this_is_it">Hello!</div>';

How do I check if the html_data var has div this_is_it ?

Trying to check using

if($(html_data).find('#this_is_it').length)

but is not working....

like image 692
andrei_1234567890 Avatar asked Jun 03 '16 18:06

andrei_1234567890


People also ask

How do I select an element in jQuery by using a variable for the ID?

The #id selector selects the element with the specific id. The id refers to the id attribute of an HTML element. Note: The id attribute must be unique within a document. Note: Do not start an id attribute with a number.

Can you select a variable in jQuery?

Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.

How do I select a specific DOM node in jQuery?

If you have a variable containing a DOM element, and want to select elements related to that DOM element, simply wrap it in a jQuery object. var myDomElement = document. getElementById( "foo" ); // A plain DOM element. $( myDomElement ).

What is $( this in jQuery?

$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.


2 Answers

.find() only searches children of the elements it's given, not the top-level elements. So you need to wrap everything in another <div>. Also, you need to fix the quoting problem that causes a syntax error -- if you use double quotes inside the string, use single quotes to delimit it, or vice versa (or escape the quotes).

var html_data = '<div class="div1">something</div><div id="this_is_it">Hello!</div>';
if ($("<div>" + html_data + "</div>").find("#this_is_it").length) {
  console.log("found");
} else {
  console.log("not found");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
like image 162
Barmar Avatar answered Sep 30 '22 21:09

Barmar


If you would just like to run a check just use indexOf() .

Example 1 :

var html_data = '<div class="div1">something</div><div id="this_is_it">Hello!</div>';

document.write(html_data.indexOf("this_is_it") > 1 ? true : false)

OR

Example 2:

FYI: Checking if length of this_is_it is greater than 1.

if(html_data.indexOf("this_is_it") > 1){

//do something here

}

Hope this helps..

like image 30
KpTheConstructor Avatar answered Sep 30 '22 21:09

KpTheConstructor