Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.has() is always true

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.


1 Answers

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") ; 
}
like image 95
Paul Roub Avatar answered Jan 30 '26 05:01

Paul Roub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!