11

how do i find if ul contains li with id 'liSubTask1' exists or not in an if condition in jquery

 <ul id='ulTask'>
   <li id='liSubTask1'>subTask1</li>
   <li id='liSubTask2'>subTask2</li>
   <li id='liSubTask3'>subTask3</li>
   <li id='liSubTask4'>subTask4</li>
   <li id='liSubTask5'>subTask5</li>
 </ul>

i wanted to find out if "li with id" exists in ul then do some thing

6 Answers6

25
if($("#ulTask #liSubTask1").length)
{
   //your code here
}
Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
6

The ">" symbol restricts a selector to direct descendents of the first selector: http://api.jquery.com/child-selector/

if ($('#ulTask > li#liSubTask4').length) {
   //...
}
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
xdazz
  • 158,678
  • 38
  • 247
  • 274
2

this sounds very familiar to these questions "Is there an “exists” function for jQuery" and "How do you check if a selector exists in jQuery?"

jQuery.fn.exists = function(){return this.length>0;}

if ($(selector).exists()) {
    // Do something
}
Community
  • 1
  • 1
Reyno
  • 583
  • 13
  • 28
1
if($('ul#ulTask li#liSubTask1').length) {
   // do stuff
}
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
0
var nextli = $("#ulTask").next(li);
var id = nextli.attr('id');
GoodSp33d
  • 6,252
  • 4
  • 35
  • 67
0

use the following code if you want to check all the inner child elements too..

if($('#ulId').find('#liId').length > 0) 
Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
Kiran
  • 111
  • 1
  • 5