How to check if an element exist into another element?
I'd like, to jQuery, understand if an element exist into another element.
Somethings like :
if($('#container').find('.search_element'))
must return YES if .search_e开发者_如何学Clement
is into #container
, NO otherwise.
How can I do it? Tried with $.contains('#container', '.search_element') but seems that this function doesnt works...
A simple length check:
if($("#container").find(".search_element").length) {
// If the length is greater than 0, it exists
} else {
// else, false
}
¡¡¡UPDATE!!!
See my answer [ HERE ] for a MUCH more robust plugin!
You could easily shorten @Chris answer with:
if($("#container .search_element").length) { ...
You could also do the same with a useful plugin i made for this:
jsFiddle
(function($) {
if (!$.exist) {
$.extend({
exist: function(elm) {
if (typeof elm == null) return false;
if (typeof elm != "object") elm = $(elm);
return elm.length ? true : false;
}
});
$.fn.extend({
exist: function() {
return $.exist($(this));
}
});
}
})(jQuery);
USE
// With your if statement
if($("#container .search_element").exist()) { ...
// With ID
$.exist("#eleID");
// OR
$("#eleID").exist();
// With class name
$.exist(".class-name");
// OR
$(".class-name").exist();
// With just tag // prolly not best idea aS there will be other tags on site
$.exist("div");
// OR
$("div").exist();
Of course this plugin could be further extended to be much more fancy (handling multiple calls at once, creating non-existing elements based on a pram), but as it stand now, it does a very simple, very needed function ... Does this element exist? return True
or False
jsFiddle
You can use .is
and :has
, just to be complete. I would prefer a solution which tests .length
though.
if($('#container').is(':has(.search_element)')) {
// I haz that
}
- http://api.jquery.com/has-selector/
- http://api.jquery.com/is/
check the length of the array
if($('#container').find('.search_element').length)
jQuery has a default method for this:
$("#container").has(".selector");
http://api.jquery.com/has/
精彩评论