Selecting only first level element, not child elements with the same element name

前端 未结 4 1230
执笔经年
执笔经年 2020-12-19 08:36

How would I select only the first level .block and not any of the children?

$(\'.block:not(\"Children of this here\")\') <--

相关标签:
4条回答
  • 2020-12-19 09:20

    Try this:

    $("div.block:first").<what you want to do>
    

    edit: removed the spaces. thanks :-)....now it should be good.

    HTH

    0 讨论(0)
  • 2020-12-19 09:22

    You can use the :first selector to select only the first matching .block element:

    $('.block:first')
    

    This works because jQuery matches elements in document order. The outermost .block element will be the first element matched by .block, and :first will filter to only return it.

    Note that :first is not the same as :first-child.

    EDIT: In response to your update, you can write the following, which will only work if all of the elements are nested three deep:

    $('.block:note(:has(.block .block))')
    

    You can write a more robust solution using a function call:

    $('.block').not(function() { return $(this).closest('.block').length; })
    

    This will find all .block elements, then remove any matched elements that have an ancestor matching .block. (You can replace closest with parent if you want to).

    0 讨论(0)
  • 2020-12-19 09:22
    $('#parent').children('.block');
    

    See .children() jQuery reference.

    0 讨论(0)
  • 2020-12-19 09:26

    If that sample markup has a parent element, for example below. If not, the parent will be body if it is valid HTML.

    HTML

    <div id="parent">
    <div class="block">
      <div class="block">
        <div class="block">
    
        </div>
      </div>
    </div>
    </div>
    

    jQuery

    $('#parent > .block').css({ border: '1px solid red' });
    
    0 讨论(0)
提交回复
热议问题