I wonder how I in the best way can see if a container div contains a child element.
Use $.contains()
, especially if performance is a concern. From the docs:
jQuery.contains( container, contained )
Returns: Boolean
Description: Check to see if a DOM element is a descendant of another DOM element.
It's more efficient than .find()
, .children()
, or .closest()
, as others have recommended. Be aware, however, that it only accepts DOM elements as parameters, not jQuery objects (which is part of why its performance is better).
In your case, you could do this in your click event handler:
if ($.contains($("#unread")[0], this)) {
alert("unread");
} else {
alert("read");
}
EDIT: Upon thinking about this again, it's probably more intuitive to search up from the clicked element, rather than down from the parent element, and performance wouldn't normally be a concern in a click event handler. That is, I would opt to use the .closest()
method (as suggested by @nnnnnn and @mu is too short), so my click event handler would contain:
if ($(this).closest("#unread").length > 0) {
alert("unread");
} else {
alert("read");
}