Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between [attribute~=value] and [attribute*=value]?

What's the difference between these two jQuery selectors?

Here are the definitions from w3schools.com:

  • The [attribute~=value] selector selects each element with a specific attribute, with a value containing a specific string.

  • The [attribute*=value] selector selects each element with a specific attribute, with a value containing a string.

UPDATE:

Here are the definitions from jquery.com. This answers my question:

  • [attribute~=value] - Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

  • [attribute*=value] - Selects elements that have the specified attribute with a value containing a given substring.

like image 728
ataravati Avatar asked Oct 10 '14 18:10

ataravati


1 Answers

*= is attributeContains selector , From jquery docs:

Selects elements that have the specified attribute with a value containing a given substring.

~= is attributeContainsWord selector , From jquery docs:

Selects elements that have the specified attribute with a value containing a given word, delimited by spaces.

See attributeContains selector with Example of usage here and attributeContainsWord selector with example and usage here

The attributeContains selector is for the string to be contained in the attribute value while attributeContainsWord selector is for string seperated with delimeted space. The official jquery examples clearly explain it.

EXPLANATION:

Attribute Contains Selector [name*="value"]

HTML:

<input name="man-news">
<input name="milkman">
<input name="letterman2">
<input name="newmilk">

JQUERY:

$( "input[name*='man']" ).val( "has man in it!" );

OUTPUT:

enter image description here

DEMO EXAMPLE:

Example of Attribute Contains Selector [name*="value"]

Attribute Contains Word Selector [name~="value"]

HTML:

<input name="man-news">
<input name="milk man">
<input name="letterman2">
<input name="newmilk">

JQUERY:

$( "input[name~='man']" ).val( "mr. man is in it!" );

OUTPUT:

enter image description here

DEMO EXAMPLE:

Example of Attribute Contains Word Selector [name~="value"]

like image 71
Ehsan Sajjad Avatar answered Oct 12 '22 04:10

Ehsan Sajjad