jQuery.has() is always true
javascript, jquery
Solution
`has()` will always return an object (a collection). That collection will sometimes be empty, which is what you want to test for:
if (jQuery(".category-products").has(".rugs-cat").length > 0)
{
jQuery(".category-products").css("margin-left", "150px")
}
else
{
jQuery(".category-products").css("margin-left", "0") ;
}
Problem
I have this HTML on one page: ``` <div class="category-products"> <div class="rugs-cat"></div> .... </div> ``` And this on another: ``` <div class="category-products"> <div class="toolbar-top"></div> ..... </div> ``` And I'm trying to add a style if `.category-products` has `.rugs-cat` as a descendant and remove it if it doesn't. I tried this (executed on dom ready): ``` if(jQuery(".category-products").has(".rugs-cat")) { jQuery(".category-products").css("margin-left", "150px") } else { jQuery(".category-products").css("margin-left", "0"); } ``` But the margin is added every time. I'm sure there is no `.rugs-cat` class anywhere in the second page.