tags:

views:

50

answers:

2
<div id="target">
<div id="test" att="test"></div>
</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.

+4  A: 
$('target').children('#test').length == 0

or

$('target > #test').length == 0
Yuriy Faktorovich
Yup changed, you're right.
Yuriy Faktorovich
Awesome. +1 Great answer :)
Doug Neiner
It doesn't work for this case:`.children('#test[att="test"]')`
you only need the ID, not the attribute test since all ids are unique
meder
+4  A: 

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

Doug Neiner
+1 For attention to *immediate* children.
Jonathan Sampson
@unknown I updated my answer to make a little jQuery plugin. It will do what you want.
Doug Neiner
No,I need to judge whether it's immediate children
Sorry, updated (both example and the plugin)
Doug Neiner
Very strange,it doesn't work with `$('> img[src="folderopen.gif"],$scope)`
You are right, but it seems to be a jQuery bug. Its really weird!
Doug Neiner
I'll post it in another question.