Alexandr Belov
Alexandr Belov

Reputation: 1834

Remove elements with the same class

I have dynamically built tabs. When you add a tab you give it a class (which is equal to the name you give to the tab), the same class is added to the tab's description, which appears beneath the default description field.

The problem is when I remove a tab I search through <li> elements and check whether they have a certain class, if they have, so they get removed. But naturally only tab itself gets removed, but not its description although the description also has the same class like the tab. Here's the fiddle.

My code which answerable for removing tabs and description is on lines 59-66 in the JavaScript section (pasted beneath).

         /*********Remove a tab******/
        $( ".close" ).click( function(){

            $( this ).closest( "li" ).fadeOut( 200, function() {$( this ).remove();});
            $thisClass = $ ( this ).closest( "li" ).attr( "class" );
            alert ( $thisClass );
            $( "li" ).hasClass( $thisClass ).remove();

        });

Upvotes: 2

Views: 1178

Answers (3)

Dzmitry Paliakou
Dzmitry Paliakou

Reputation: 1627

If you have the same situation as described in fiddle, then

  1. you need to remove class 'item' from li classes list
  2. correct mistake with hasClass

and you'll get something like this

        $( ".close" ).click( function(){

            $( this ).closest( "li" ).fadeOut( 200, function() {$( this ).remove();});
            $thisClass = $ ( this ).closest( "li" ).attr( "class" ).replace('item ','');
            alert ( $thisClass );
            $( "li."+$thisClass ).remove();
        });

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227240

$thisClass = $ ( this ).closest( "li" ).attr( "class" );

This will return you all the classes on the element. That element may have more than one class. If it does, then you'll get a space-separated list of them.

Also hasClass() returns a boolean. It tells you whether an element has a class or not.

You want to do this:

$( 'li.'+$thisClass.replace(' ', '.') ).remove();

Upvotes: 0

Edu Ruiz
Edu Ruiz

Reputation: 1877

try change $( "li" ).hasClass( $thisClass ).remove(); to $('.'+$thisClass).remove();

Upvotes: 1

Related Questions