andrei_1234567890 andrei_1234567890 - 6 months ago 10
jQuery Question

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....

Answer

.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>

Comments