0

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

2
  • 4
    Don't know if that's the only problem, but setting display attr to none will do nothing (there is no display attribute into the element). display is a css property. In order to hide your elements with jQuery, ou can use $(cmp).css("display","none"); or $(cmp).hide() (with parentheses). Commented Feb 13, 2017 at 16:05
  • you can simplify it to $(".product [id$=" + id_get + "]").hide() Commented Feb 13, 2017 at 16:09

1 Answer 1

3

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();
        }
    });
}
Sign up to request clarification or add additional context in comments.

6 Comments

Have you tried to debug it? Are you sure your id's match up?
If you post more of your html code, we might be able to see what else could be going on. As it is now, we're driving blind. My answer could be only part of the solution. There could be something else going on as well.
the problem was that i had a class named "A+++",why i can't?
Not sure what you mean there. Can't what?
<div id="A+++_OT"> this doesn't work, <div id="_OT"> this works
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.