Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove children with defined attribute - not working

Trying to remove children DIV elements of a parent with certain attribute. I have it half working, but with the below code, it doesn't find the children

HTML

<div id="PremiumGiftContainer" class="PremiumGiftContainer">

     <div class='message' is-vip='false'>
      <p>FALSE</p>
    </div> 

    <div class='message'  is-vip='false'>
      <p>FALSE</p>
    </div>

    <div class='message'  is-vip='true'>
      <p>TRUE</p>
    </div>

</div>

<button id="button">Remove</button>

JQUERY

$("button").on("click", function(){
  remove_element();
})

function remove_element(){

      $('#PremiumGiftContainer').children(function () {

        $("[is-vip]").each(function(){
          if($(this).attr('is-vip')=='true'){
            $(this).fadeOut();
          }
        });

      })
}

FIDDLE

If I remove the $('#PremiumGiftContainer').children... section, it works, but I was trying to limit the scope of the search that needs to happen to find the correct switches.

Is what I'm trying to do achievable?

like image 397
SteveV Avatar asked Feb 03 '26 15:02

SteveV


1 Answers

children() does not accept a function, it takes a selector. As such you can simply use an attribute selector and then call fadeOut() on the resulting elements.

Also note that you should not create your own non-standard attributes on elements. If you want to store custom data with an element, use a data-* attribute.

$("button").on("click", function() {
  remove_element();
})

function remove_element() {
  $('#PremiumGiftContainer').children('[data-is-vip="true"]').fadeOut();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="PremiumGiftContainer" class="PremiumGiftContainer">
  <div class="message" data-is-vip="false">
    <p>FALSE</p>
  </div>
  <div class="message" data-is-vip="false">
    <p>FALSE</p>
  </div>
  <div class="message" data-is-vip="true">
    <p>TRUE</p>
  </div>
</div>

<button id="button">Remove</button>
like image 54
Rory McCrossan Avatar answered Feb 06 '26 04:02

Rory McCrossan