samir chauhan
samir chauhan

Reputation: 1525

Jquery find is not working

This is the Html for my page I just want if there are no popular products then the whole div popular_prd should hide.

<div class="popular_prd">
    <h1 class="views-heading">Popular Products</h1>
    <div class="view view-popular-products view-id-popular_products view-display-id-default boxes-bottom view-dom-id-3">
        <div class="views-admin-links views-hide">
            <ul class="links">
                <li class="0 first">
                    <a href="/admin/build/views/edit/popular_products?destination=node#views-tab-default">Edit</a>
                </li>
                <li class="1">
                    <a href="/admin/build/views/export/popular_products">Export</a>
                </li>
                <li class="2 last">
                    <a href="/admin/build/views/clone/popular_products">Clone</a>
                </li>
            </ul>
        </div>
    </div>
</div>

I used the following jquery code to hide tthe div.

$('document').ready(function(){
if(!$('.popular_prd').find('.view-content') ) {
        $('.popular_prd').hide();
    }
    else {
    $('.popular_prd').show();
    }
});

But the code is not working the div is still showing up.

Upvotes: 0

Views: 2021

Answers (5)

JohnP
JohnP

Reputation: 50029

$('.popular_prd').find('.view-content')

This will just return a jQuery object which never evaluates to false

You need to check the length of it

if(!$('.popular_prd').find('.view-content').length) {
  //no products.
}

Upvotes: 5

harpo
harpo

Reputation: 43228

find doesn't work the way you think. It looks like instead of

if(!$('.popular_prd').find('.view-content') ) {

what you mean is

if(!$('.popular_prd').find('.view-content').length ) {

In fact, you don't even need find here...

if(!$('.popular_prd .view-content').length ) {

Bottom line, jQuery selectors don't return true or false, but a set. Test the length to see whether anything was found.

Upvotes: 4

S L
S L

Reputation: 14328

Or use length property

$('document').ready(function(){
if(!$('.popular_prd').find('.view-content').length) {
        $('.popular_prd').hide();
    }
    else {
    $('.popular_prd').show();
    }
});

Upvotes: 2

Naveed Butt
Naveed Butt

Reputation: 2901

view-content class is not contained in the div with class popular_prd in the above HTML

Upvotes: -1

Bemmu
Bemmu

Reputation: 18247

You don't have a view-content class in your HTML.

Upvotes: 0

Related Questions