I assume data
is a string containing HTML markup. If so, then:
var tree = $(data);
if (tree.find("#Mydiv")[0]) {
// An element with the `id` "Mydiv" exists in the tree
}
You don't have to use a variable, you could just do this:
if ($(data).find("#Mydiv")[0]) {
// An element with the `id` "Mydiv" exists in the tree
}
...but I just assume you're probably going to want to do something else with tree
afterward, so we want to avoid parsing it more than once.
Note: If the "Mydiv" element may be at the top level of the HTML in data
, you'll want to wrap that structure in a parent element for the above to work (there are other ways, but they're more complicated). So if that may be the case, use $("<div>" + data + "</div>")
rather than just $(data)
. This is because find
searches descendant elements, so if the HTML were "hi", it wouldn't find it as it's not a descendant (it's the element itself).
Update: Here's a live example