简体   繁体   中英

How to remove elements of a certain class inside a parent element Jquery

I have a span that contains category buttons, and when clicked the subcategory buttons are added within the parent span. The purpose of it is that when the category button is clicked again, if the subcategories have already been populated, it should remove them, like so:

$('.catBtns').on('click', function() {
    var catId = parseInt(this.id);
    if ($('#' + catId).parent().find('button').length <= 1) {
        $.each(data.category[catId].subcategory, function(i) {
            $('<button class="subcatBtns" id="'
              + data.category[catId].subcategory[i].subcategoryId + '">'
              + data.category[catId].subcategory[i].subcategoryName.split('<--name-->')[currentLang]
              + '</button>').appendTo($('#' + catId).parent());
            i++;
        });
    } else {
        $('#' + catId).parent().remove('.subcatBtns');
    }
});

So far no luck. Why am I unable to remove all elements of class subcatBtns from the parent element of the category button? The jquery API for the remove() method has this example:

$( "div" ).remove( ".hello" );

Is it because of the parent() method before it? Should I just add a specific Id to the span instead of selecting it through the ID of the child? The HTML is very simple, here:

   <nav id="nav">
        <img src="img/resources/logo.png" alt="logo" id="logoMenu">
        <span id="span0" class="catSpan">
            <button class="catBtns" id="0">EN-0</button>
            <button class="subcatBtns" id="000">EN-000</button>
            <button class="subcatBtns" id="001">EN-001</button>
        </span>
        <span id="span1" class="catSpan">
            <button class="catBtns" id="1">EN-1</button>
        </span>
        <span id="span2" class="catSpan">
            <button class="catBtns" id="2">EN-2</button>
        </span>
        <span id="span3" class="catSpan">
            <button class="catBtns" id="3">EN-3</button>
        </span><span id="span4" class="catSpan">
            <button class="catBtns" id="4">EN-4</button>
        </span>
    </nav>

The .remove() method removes the elements on which it is called , optionally filtered by a selector. In the line

$('#' + catId).parent().remove('.subcatBtns');

You define a set of matched elements which contains only one element (the button container) and then call .remove() on this set with the selector ".subcatBtns" . Since the container does not match the selector, nothing gets removed.

Try, instead:

$('#' + catId).parent().find('.subcatBtns').remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM