9

I'm trying to find all the parent elements that have the CSS style display:none. I can't seem to get it to work though. Here's what I've got:

var $parents = $(...).parents("[css=display:none]");

4 Answers 4

18

If you want the ones that are actually display: none; (not just possibly contained in another display: none;), you can use .filter() and .css() to get those parents, like this:

var $parents = $(...).parents().filter(function() {
                  return $(this).css('display') == 'none';
               });

This gets the parents, then filters them to get only the ones that are display: none; on that specific parent.

Sign up to request clarification or add additional context in comments.

Comments

9

@Nick's solution is a very simple and straightforward method of achieving your goal. It's also probably the best performing method. However, for the sake of completeness and convenience (if you're doing this a lot), it's also possible to create your own selector:

$.expr[':'].css = function(obj, index, meta, stack) {
    var args = meta[3].split(/\s*=\s*/);
    return $(obj).css(args[0]) == args[1];
}

// Then we can use our custom selector, like so:
$("#myElement").parents(":css(display=none)").show();

Example - http://jsfiddle.net/V8CQr/.

See more information on creating custom selectors at:

http://www.jameswiseman.com/blog/2010/04/19/creating-a-jquery-custom-selector/

Comments

1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('a').parents('div[style*="display: none"], [style*="display:none"]').show();
        });
    </script>
</head>
<body>
    <div class="Test" style="color: Red; display: none;">
        aaa <a href="#test">test</a><br />
    </div>
    <div class="Test" style="color: Aqua;">
        bbb <a href="#test">test</a><br />
    </div>
    <div class="Test" style="font-size: 15px; display: none;">
        ccc <a href="#test">test</a><br />
    </div>
</body>
</html>

Comments

1

You were close:

$(...).parents('[style*="display: none"]');

Note: this does a substring search on element attribute values so it's not as good as the $(this).css(...) filter solution shown above.

The docs.

Comments

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.