jQuery Selector [attribute~=value] by attribute sub word

Introduction

The [attribute~=value] selector selects elements by value specific sub string.

The string can contain whitespace.

$("[attribute~='value']")
Parameter Optional Description
attribute Required. the attribute to find
value Required.the string value

Select all <input> elements with a name attribute that contains the specific word "flag":

It will select the attribute name that contains the specific string "flag", and not the attribute name that starts, includes or ends with "flag".

View in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("input[name~='flag']").css("background-color", "yellow");});
</script>//  ww w  .java 2 s  . c o m
</head>
<body>

<input name="flagMark" type="text" value="CSS">
<input name="flag" type="text" value="HTML">
<input name="myflag" type="text" value="Java">
<input name="anotherflag" type="text" value="Javascript">
</body>
</html>



PreviousNext

Related