jQuery using 'this' in an if statement

Go To StackoverFlow.com


I'm using an if statement in order to determine if an element has any children. If it does NOT have any children, I want to do something to that element only.

Here's the premise of what I'm trying to do:

if ($("#div a").children().length > 0){

So if an <a> tag has no children, I want to do something to that specific element (or multiple elements that also have no children).

The problem is that this hasn't been defined because it's an if statement.

I could be completely missing something but I'm not quite sure how to accomplish this. Any advice would be appreciated

2012-04-03 22:17
by scferg5


Edit: Added DEMO Link

You can use .filter to check the condition and call .hide on the filter results. See below,

$("#div a").filter(function () {
  return ($(this).children().length > 0)
2012-04-03 22:20
by Selvakumar Arumugam
Perfect, works great. Thanks - scferg5 2012-04-03 22:33


you could use each to iterate through elements

  if ($(this).val()) {
2015-10-09 00:02
by user3716779


Simple solution is to place the element in a variable.

var elem = $("#div a");
if (elem.children().length > 0){
2012-04-03 22:21
by Dustin Laine
Not sure if your answer would really work if #div has multiple a tags. http://jsfiddle.net/skram/bxDNq/5 - Selvakumar Arumugam 2012-04-03 22:27
@SKS, Good point, + - Dustin Laine 2012-04-03 22:54