1

Given this simple ul:

<ul class="dummy">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

And this jQuery code:

var container = $('.dummy');
var active = container.children('li.active') || container.children('li:first-child')
console.log(active.html());

According to what I know about using || in variable assignment, I'd expect that the first li should be selected, since there are no li.active (see also this thread)

Instead, in the console.log I get undefined instead of One: seems that the container.children('li:first-child') is never evaluated

Where am I wrong? Here is a JSFiddle... Thanks a lot!

Ivan
  • 2,463
  • 6
  • 39
  • 51
  • see this for AND, OR operations:: https://stackoverflow.com/questions/10687131/jquery-select-by-attribute-using-and-and-or-operators – Sudhir Bastakoti Jul 03 '17 at 10:42
  • try writing the inline like this: `(container.children('li.active') || container.closest('li') ? true : false)` – treyBake Jul 03 '17 at 10:44
  • 1
    `container.children('li.active')` will never be null/undefined as it will always be a JQuery object, whether or not it has any elements is a different matter. – phuzi Jul 03 '17 at 10:46
  • phuzi is right, consider using [.length](https://api.jquery.com/length/). See updated [JSfiddle](https://jsfiddle.net/zfatv1ft/2/) – Gjermund Dahl Jul 03 '17 at 10:48

2 Answers2

1

As jQuery method returns a jQuery object which will always be truthy; thus you are getting undefined. if you are only intending to get HTML you can use.

var active = container.children('li.active').html() || container.children('li:first-child').html();

However you want to get the element, do away with || and use .length property to check if element exists.

var active = container.children('li.active');
if(active.length == 0)
    active = container.children('li:first-child')

var container = $('.dummy');
var active = container.children('li.active').html() || container.children('li:first-child').html()
console.log(active);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dummy">
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

The following values are considered as "false" in JavaScript.

  • false
  • null
  • "" (empty string)
  • 0
  • Nan
  • undefined

The || operator will work for those cases. In your case container.children('li.active') is not returning anyone of above value, It is jquery selector object. So in this case the second option will not execute.

Please console this statement you will get some clarification. console.log(container.children('li.active'))

Honey
  • 366
  • 2
  • 4
  • 17