Val55 Val55 - 4 months ago 24
Javascript Question

How to check if data-attribute does not contain a string with :contains in jQuery

Is it possible to apply

:not(:contains())
selector to data-attribute? Here is what I have in HTML:

<input id="keyword">
<button id="find1">Find - 1</button>
<button id="find2">Find - 2</button>

<div class="list_item" data-stringtofind="abc def">abc def</div>
<div class="list_item" data-stringtofind="ghi jkl">ghi jkl</div>
<div class="list_item" data-stringtofind="mno prs">mno prs</div>


What I'd like to do is to filter it on click based on what is inside of
data-stringtofind
attribute. I'm trying with this code, but it's not working.

$('#find1').on('click', function () {

var findthis = $('#keyword').val();

console.log(findthis);

$( ".list_item.data('stringtofind'):not(:contains("+ findthis +"))").hide();
console.log(".list_item.data('stringtofind')");

});


Here is what the console outputs:

Error: Syntax error, unrecognized expression: .list_item.data('stringtofind'):not(:contains(abc))


Am I doing some simple mistake or this just isn't possible to do with :not:contains?

This code works, but it searches inside of the div, not inside of the data-stringtofind attribute.

$('#find2').on('click', function () {
var findthis = $('#keyword').val();

console.log(findthis);

$( ".list_item:not(:contains("+ findthis +"))").hide();
console.log(".list_item.data('stringtofind')");

});


Here is a fiddle: https://jsfiddle.net/mk7yr62k/2/

Answer

:contains isn't related to attributes at all. You want an attribute substring selector:

$( ".list_item:not([data-stringtofind*='" + findthis + "'])").hide();

[data-stringtofind*='xxx'] means "xxx anywhere in the data-stringtofind attribute." And of course, :not negates it.

Here's an example:

var p = $("<p>").text("Waiting briefly...").appendTo(document.body);
setTimeout(function() {
  var findthis = "abc";
  $( ".list_item:not([data-stringtofind*='" + findthis + "'])").hide();
  p.text("Hid the ones not matching 'abc'");
}, 500);
<div class="list_item" data-stringtofind="abc def">abc def</div>
<div class="list_item" data-stringtofind="ghi jkl">ghi jkl</div>
<div class="list_item" data-stringtofind="mno prs">mno prs</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Comments