<div id="target">
<div id="test" att="test"></di开发者_Go百科v>
</div>
$('target').haschild('#test')
should be true
$('target').haschild('#test[att="test"]')
should be true
$('target').haschild('#no')
should be false
Only $('target')
is available.
$('target').children('#test').length == 0
or
$('target > #test').length == 0
You can test a few ways, here is one:
if($("#target > #test").length){
//true
} else {
//false
}
If you play with jQuery plugins, you can actually use the syntax you use in your example:
$.fn.haschild = function(selector){
return ($("> " + selector, this).length > 0);
}
$(function(){
alert($('#target').haschild('#test')); // Alerts true
alert($('#target').haschild('#test[att="test"]')); // Alerts true
alert($('#target').haschild('#no')); // Alerts false
});
Here is a working example
Modifying an example found here to suit this example, you can extend JQuery to have a new :haschild selector, as well as the method,
The you can use $('#target:haschild(#test)')
as well as .haschild('#test')
$.fn.haschild = function(selector){
function filterMethod(){
if (selector) {
return $(this).children(selector).length >= 1;
}
return $(this).children().length >= 1;
}
return this.filter(filterMethod);
}
$.expr[':'].haschild = function(objNode,intStackIndex,arrProperties,arrNodeStack){
var selector = arrProperties[3];
if (selector) {
return $(objNode).children(selector).length >= 1;
}
return $(objNode).children().length >= 1;
}
精彩评论