jqueryjquery-selectorsjquery-attributes

jQuery Inverse of Selection


Give the code below, I want to select only those divs that have a data-PType attribute containing ABC or DEF or GHI. In the listing below then, I want to select divs with ids 1, 3 and 5.

I also need a second selection of all divs where the data-PType attribute contains none of the follow: ABC, DEF GHI. In the listing below then, I want to select divs with ids 2 and 6.

You can see the second selection is essentially the negation of the divs in the first selection. I was hoping it might be possible to express the second selection in terms of the inverse or negation of the first, somehow.

Note that the div with id='4' should never be selected since it has no data-PType attribute.

<div id="1" data-PType="ABC"></div>
<div id="2" data-PType="QST"></div>
<div id="3" data-PType="ABC DEF"></div>
<div id="4"></div>
<div id="5" data-PType="GHI"></div>
<div id="6" data-PType="UVW"></div>

Solution

  • If you prefer jquery selectors,

    var sel1 = $("[data-PType*='ABC'],[data-PType*='DEF'],[data-PType*='GHI']");
    var sel2 = $("div[data-PType]:not([data-PType*='ABC']):not([data-PType*='DEF']):not([data-PType*='GHI'])");
    console.log.apply(console, sel1);
    console.log('---------');
    console.log.apply(console, sel2);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="1" data-PType="ABC"></div>
    <div id="2" data-PType="QST"></div>
    <div id="3" data-PType="ABC DEF"></div>
    <div id="4"></div>
    <div id="5" data-PType="GHI"></div>
    <div id="6" data-PType="UVW"></div>