1

I need to select an element based on what is not inside it's element.

<div class="person">
  <div class="name">Jason</div>
</div>

<div class="person">
</div>

What do I need to do to select the second div with the person class. I know there are has and not properties, do I need to combine them in some way to get this to work?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Mary
  • 13
  • 2

3 Answers3

2

You can use as selector:

$(".person:not(:has(.name))")

But i'd suggest you to filter it instead:

Because :has() is a jQuery extension and not part of the CSS specification, queries using :has() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method.

$(".person").filter(function(){
    return !$(this).find(".name").length;
})

-jsFiddle-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • I wouldn't worry too much about the inefficiency of `:has`. I guess that jQuery does something much like the `.filter()` solution internally so the two solutions are, in all probability, pretty similar. – Roamer-1888 Mar 05 '15 at 19:38
  • @Roamer-1888 Ya this is basically what is doing `:has()` but there was some bugs regarding this pseudo selector, however fixed on jq >1.8.2. – A. Wolff Mar 05 '15 at 19:47
  • Ouch, that means it must have been buggy for some years from v 1.1.4 to v1.8.1 – Roamer-1888 Mar 05 '15 at 20:09
  • There's also the fact that jQuery selectors are often confused with CSS selectors - the question was mistitled and mistagged, which I have now fixed, but some of the downvotes could have come from this misunderstanding. – BoltClock Mar 06 '15 at 03:07
1

Simplest jquery solution $('.person:empty'), but second div must be without space

<div class="person">
  <div class="name">Jason</div>
</div>

<div class="person"></div>
marsh
  • 1,431
  • 1
  • 13
  • 19
0

You can go for something like this,

function getPersonWithNoNameField() {
  $('.person').each(function() {
    if($(this).find('div.name').length === 0) {
      var ele = $(this);
      console.log(ele.html());
      return ele;
    }
  });
}

getPersonWithNoNameField();

For your need, you can customise the function to return element which you want.
Nielarshi
  • 1,126
  • 7
  • 11