简体   繁体   中英

Select all parents with class

How can I select all parent elements that have one specific class? For example:

<ul class="123">
  <li>
  <li>
    <ul class="qwe">
      <li>
      <li>
        <ul class="123">
          <li class="select">
          <li>
        </ul>
    </ul>
</ul>

How can I select all parent ul elements according to the li with class 'select' that have class '123'?

Is this what you're looking for?

$('.select').parents('.123');

Or maybe the more specific:

$('li.select').parents('ul.123');

How about an alternative using the has() method:

$("ul.123").has("li.select")

http://jsfiddle.net/6wB49/


has()

Description : Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

jquery-class-selectors

$('ul[class="123"] li.select');

//Or

$('li.select').parents('ul.123');

Hi,

You can also try this....

<head runat="server">
    <title></title>
    <script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('ul').bind('click', function () {
                $(this).parent().each(function () {
                    alert($(this).attr('title'));
                });
            });
            $('li').bind('onclick', function () {
                $(this).parent().each(function () {
                    alert($(this).html());
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div title="div">
        <ul class="123" title="1111_1">
            <li title="test_1">Test 1</li>
            <li title="test_2">Test 2</li>
            <ul class="qwe" title="qwe">
                <li title="qwe_1">ABC 1</li>
                <li title="qwe_2">ABC 2</li>
                <ul class="123" title="123">
                    <li class="select" title="123_1">XYZ 1</li>
                    <li title="123_2">XYZ 2</li>
                </ul>
            </ul>
        </ul>
    </div>
    </form>
</body>
</html>

Thank you, Vishal Patel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM