jQuery > Selectors

element[attribute~='value' - Attribute contains value in mid in jQuery

How to select elements whose attribute value contains certain characters only in between?


To select elements whose attribute value contains certain characters only in between, we can use "~=" operator.

   <input id="txtName" type="text" data-id="txtName" />
    <input id="FirstNameLast" type="text" data-id="Name txt" />
    <input type="button" value="Button" id="btnTest" />

    <script>
        $(function () {
            $("input[data-id~='Name']").css("border", "1px solid red");
            // $("input[id*='Name']").css("border", "1px solid green");
        });
    </script>

 Above jQuery code snippet wouuld select only 2nd element as "Name" characters are in between id attribute value only in the second element id. Notice that 1st element also has "Name" in its id attribute however it comes in the last of the word so that would not get selected.

Attribute contains characters in between

To find out elements whose attribute value contains certain characters anywhere in it, read contains selector.

 Views: 6188 | Post Order: 23



Write for us






Hosting Recommendations