Search code examples
jqueryjquery-filter

Remove from set of matched Elements with jQuery


I have the following example html:

<div id="root">
    <span>A</span><!--select-->
    <span>B</span><!--select-->
    <div>
        <span>C</span>
        <span>D</span>
        <div>
            <span>E</span>
        </div>
    <div>
    <p>
        <span>F</span><!--select-->
        <div>
            <span>G</span>
        </div>
    </p>
</div>

I want to select all spans except the ones, that are childs of other divs. spans that are children of other elements (such as p, button or anything else) shoud be selected. The p is just an example. This means I want to have span A, B and F. I tried:

$("#root").find("span").not("div span");

But .not("div span") removes all spans as the root Element is also a div. Is there a way with jQuery?


Solution

  • You can try

    $('#root span').not('#root div span').css('color', 'red')
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="root">
      <span>A</span>
      <!--select-->
      <span>B</span>
      <!--select-->
      <div>
        <span>C</span>
        <span>D</span>
        <div>
          <span>E</span>
        </div>
      </div>
      <p>
        <span>F</span>
        <!--select-->
        <div>
          <span>G</span>
        </div>
      </p>
    </div>

    Note: Your html is invalid as p can't have div element as its child.