user1038814
user1038814

Reputation: 9657

Removing an item from a list having a particular class using Jquery

I have a dropdown, which when a particular option is selected removes an item from a list which has a certain class. However, my remove command: $('#coll-grouped-list li').hasClass('timeGroup').remove(); doesn't seem to work. Any ideas?

HTML

<select id="tGroup" name="tGroup" class="standard_select" style="width:200px;">
                  <option value="">Please Select</option>
                  <option value="hourGroup">Group by Hour</option>
                  <option value="dayGroup">Group by Day</option>
                  <option value="weekGroup">Group by Week</option>
                  <option value="monthGroup">Group by Month</option>
                  <option value="yearGroup">Group by Year</option>
                </select>

<ul id="coll-selected-list" class="droptrue sort-drop">
              </ul>
<ul id="coll-grouped-list" class="droptrue agg-drop">
              </ul>

JS

$('#tGroup').bind('change', function (e) { 
        if( $('#tGroup').val() == 'hourGroup') {
          $('#coll-grouped-list li').hasClass('timeGroup').remove();
          $("#coll-grouped-list").append('<li class="timeGroup">Hour</li>');
        }
        if( $('#tGroup').val() == 'dayGroup') {
          $('#coll-grouped-list li').hasClass('timeGroup').remove();
          $("#coll-grouped-list").append('<li class="timeGroup">Day</li>');
        }         
      });

Upvotes: 0

Views: 1898

Answers (3)

Ram
Ram

Reputation: 144669

Try this:

 $('#tGroup').bind('change', function (e) { 
     var $group = $('#coll-grouped-list');
     if( this.value == 'hourGroup') {
       $group.find('li.timeGroup').remove();
       $group.append('<li class="timeGroup">Hour</li>');
     }
     if( this.value == 'dayGroup') {
       $group.find('li.timeGroup').remove();
       $group.append('<li class="timeGroup">Day</li>');
     }         
  });

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

It doesn't work because .hasClass() returns a boolean value, not a jQuery object, so you can't chain another jQuery function (.remove()) afterwards.

Try this instead:

$('#coll-grouped-list li.timeGroup').remove();

Upvotes: 0

Andreas Wong
Andreas Wong

Reputation: 60516

hasClass returns boolean, so intuitively, it's not chainable, thus doing what you are doing in the example is invalid, as there's no method remove() in boolean class (true.remove())

Try

$('#coll-grouped-list li.timeGroup').remove(); 

From the docs:

The .hasClass() method will return true if the class is assigned to an element

Upvotes: 1

Related Questions