Home > OS >  Check if "data" attribute contains A PART of input value (jQuery)
Check if "data" attribute contains A PART of input value (jQuery)

Time:07-30

With this way I only find the needed div, if the "data-content" contains the complete word.

var input = "TestText123";
var found = $("#list").find(".box[data-name='"   input   "']").addClass("found");

But I also want to find this div if my "input" just contains a correct part of it (min. 5 characters).

It's interesting, that this would work, if I don't use the "data" method (but I need it).

var found = $("#list").find(".box:contains('"   input   "')").addClass("found");

How to modify the "data" method in jQuery, like the way I need it?

CodePudding user response:

Add an asterisk before the equal sign: [data-name*=...].

Side note: the argument of addClass should not have a dot, so just addClass("found"):

var input = "TestText123";
var found = $("#list").find(".box[data-name*='"   input   "']").addClass("found");
.found { background: yellow }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul id="list">
    <li class ="box" data-name="WhatTestText12345">should match</li>
</ul>

  • Related