0

I'm trying to hide a button if it has a class "List" and if not display it. On load itself I'm displaying the button, and later if that has a class, I'm hiding it using jquery. It works too!. But I'm not sure that it is the best way to do it. Any suggestions? Here is my code

$('.ProductList').parent().find('.CompareButton').show();
   if($('ul.ProductList').hasClass('List')) {
           $(this).find('.CompareButton').hide();
   } 

5 Answers 5

3

Try to change this part

$(this).find('.CompareButton').hide();

into:

$('.CompareButton').hide();
Sign up to request clarification or add additional context in comments.

Comments

0

i dont think $(this) will refer to $('ul.ProductList') as per your given code.

you may have to try out

$('ul.ProductList').find('.CompareButton').hide();

instead of

$(this).find('.CompareButton').hide();

2 Comments

@Sateesh, No. I need to check if <ul class='ProductList'> has that class, then only I need to hide it.
@NizamAli : I am not telling you to remove all code. just that the $(this) u are refering to will not refer to the object you are expecting it to be.
0

By default if you want to display it then assign display:block in your html code, later on ready document you can call a function to hide it

$(document).ready(function() {
showButton();

});

function showButton() {
if($('ul.ProductList').hasClass('List')) {
           $(this).find('.CompareButton').hide();
   } 

}

1 Comment

I shouldn't write any code on HTML code. I need to write only in JS file.
0

The easily thing is add to your css 2 statement one without class list display:block & One With class list display:nonelike this .
when you add the class. Statement 2 will be Evaluted & when you removed Statement 1 will be Evaluted.

ul.ProductList.List  {display:block}
ul.ProductList.List .CompareButton {display:none}

Comments

0

Your jquery code can be at least shortened a bit.

// this can be shown in css by default
$('.ProductList').parent().find('.CompareButton').show(); 
//this replaces your if statement
$('.ProductList.List').parent().find('.CompareButton').hide();

But better way would be to hide what you need in css without using javascript at all.

3 Comments

The condition is I shouldn't use any css code or any HTML code. So, that's why I need to check it using IF condition
$('.ProductList.List') would select ul that has both .ProductList and .List, isnt that what you want?
I need to check whether <ul class='ProductList'> it has the class 'List' or not. If not then I shouldn't compile that statement. I hope that makes sense :)

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.