0

I have wrapper with two randomly injected kinds of banners on site - one at time - only difference is that one kind uses data-abcde-zoneid="10" and second is not. I have to select those that doesn't contain data-abcde-zoneid="10" where abcde is random string and do some things with it.

Searching only by value or adding class to that element isn't possible. The only solution is to find element which contains -zoneid="10" or opposite to it. I can't change injected html for banners.

I'm aware of finding class name or attribute value like in jQuery: Finding partial class name and I've tried use those to find solution but with no result.

kruzyk
  • 5
  • 3

1 Answers1

0

Although there are duplicates out there, they were very verbose so I decided to post some shorter versions:

You can filter - if you need, change the zoneid and value to vars and wrap in a function:

jQuery with ES6 fiddle

$("div").filter(
    (_, div) => (
      Array.from(div.attributes).filter( // Array from NamedNodeMap
        (item) => item.name.indexOf("zoneid") !== -1 && item.value !== "10")
    ).length > 0
  )
  .addClass("red")
.red {
  background-color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-xxxxx-zoneid="10">
  XXXXXX 10
</div>
<div data-xxxx-something-else="z" data-xxxxx-zoneid="20">
  XXXXXX 20
</div>
<div data-yyy-zoneid="10">
  yyy 10
</div>
<div data-yyy-zoneid="30">
  yyy 30
</div>

jQuery for older browsers fiddle

$("div").filter(function() {
    var namedNodeMap = this.attributes;
    for (var i = 0; i < namedNodeMap.length; i++) {
      var item = namedNodeMap.item(i);
      if (item.name.indexOf("zoneid") !== -1 && item.value !== "10") {
        return true
      }
    }
  })
  .addClass("red")
.red {
  background-color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-xxxxx-zoneid="10">
  XXXXXX 10
</div>
<div data-xxxx-something-else="z" data-xxxxx-zoneid="20">
  XXXXXX 20
</div>
<div data-yyy-zoneid="10">
  yyy 10
</div>
<div data-yyy-zoneid="30">
  yyy 30
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236