4

I need help with the below jQuery, it's not working for me. I want to fire some actions only if <optgroup label="Knowledge Base"> does not exist

My HTML (which can't be changed):

<select id="entry_forum_id" name="entry[forum_id]">
<optgroup label="Knowledge Base"> … </optgroup>
<optgroup label="Incidents"> … </optgroup>
<optgroup label="Articles"> … </optgroup>
</select>

My jQuery attempt:

if($('optgroup:not([label="Knowledge Base"])')) {
    alert('test');
}
James A Mohler
  • 11,060
  • 15
  • 46
  • 72
user2526777
  • 75
  • 1
  • 6

2 Answers2

6

$('optgroup:not([label="Knowledge Base"])') returns a jQuery wrapper object, you need to test its length property to check whether it contains any elements

You need to test

if($('optgroup[label="Knowledge Base"]').length == 0) {
    alert('test');
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
5

I don't think you need the pseudo-selector :not. Just check there are no optgroup with that label:

if($('optgroup[label="Knowledge Base"]').length == 0) {

Fiddle.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260