-2

I render the html in php ,and use jQuery .they have such html code :

<div>
    <tr class="selectClass"></tr>
    <tr class="selectClass"></tr>
</div>

In some condition , it will remove this <tr class="selectClass"></tr>, and become :

<div>

</div>

I have to judge this two situations ,I try different way , but the result is strange .

  var selectTr  = $('.selectClass') ;

   if( selectTr ){
      console.log("i am undefined") ; 
   }

it do not print anything .

  var selectTr  = $('.selectClass') ;

   if( typeof (selectTr) == "undefined"  ){
      console.log("i am undefined") ; 
   }

it do not print "i am undefined " . so i try it console.log(typeof (selectTr)) , it is object .

My problem is that :

how to judge a empty object and why it is object instead of null or undefined?

Mattia Dinosaur
  • 891
  • 10
  • 29
  • 2
    The provided HTML is invalid, `div` is not a permitted parent for [`tr`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr). – Teemu Aug 30 '17 at 09:51
  • Firstly, you cannot have `tr` elements as children of a `div`. Secondly, use the `length` property to determine how many elements were found by the selector. – Rory McCrossan Aug 30 '17 at 09:52
  • 1
    An empty DOM object is not undefined. It is defined. It just doesn't have any children. I suggest studying real javascript. – NonameSL Aug 30 '17 at 10:04

1 Answers1

3

You have to check the length of the selected element like

if($('.selectClass').length === 0){
   //there is no element with the class selectClass
}

This is the best way to achieve what you want.

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62