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....
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.
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.
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 ).
$(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.
.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>
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With