Jack_usti
Jack_usti

Reputation: 99

How to hide item in html with jquery using variable

i'm trying to use this simple script to hide some element by ID, i have the id in a variable but it doesn't work.. this is the code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
function filter(id_get) {
  $(".product").each(function(index) {
    var f = this.id;
    if (!f.includes(id_get)) {
      var hash = "#";
      var cmp = hash.concat(f);
      $(cmp).attr("display", "none");
    }
  });
}
</script>

if i do a console.log(cmp) it displays correct product id to remove, but it doesn't hide the div.

i've also tried $(cmp).hide

Upvotes: 0

Views: 88

Answers (1)

Matt Spinks
Matt Spinks

Reputation: 6698

You are attempting to change an attribute directly. display is not an attribute. style is an attribute. You can change the display property of the style attribute. Change $(cmp).attr("display","none"); to:

$(cmp).css("display", "none");

Or, you can just use the built in jQuery hide function. Change $(cmp).attr("display","none"); to:

$(cmp).hide();

In context:

function filter(id_get){
    $( ".product" ).each(function( index ) {
        var f = this.id;
        if(!f.includes(id_get)){
          var hash = "#";
          var cmp = hash.concat(f);
          $(cmp).hide();
        }
    });
}

Upvotes: 3

Related Questions