CSS Attribute Selectors
What is it?
CSS attribute selectors can be used as locators to identify elements on a web page. These selectors allow you to target elements based on their attribute values.
CSS attribute selectors are useful when you need to locate elements based on attributes such as type, href, src, etc., rather than just relying on tag names, classes, or ID.
Difference between CSS Attribute Selectors and CSS simple selectors
CSS simple selectors target elements based on their tag name, class, or ID.
However, they may not be sufficient when you need to target elements based on their attribute values.
CSS Attribute Selectors allow you to target elements based on their attribute values.
They provide more flexibility in locating elements that have specific attribute values or patterns. Here are some examples of CSS attribute selectors.
Here is the sample HTML .
<input class="name" id="firstName" name="fname" placeholder="First Name" fdprocessedid="wo80jr">
<input placeholder="Enter your security question" type="text" fdprocessedid="1pw2v6">
There are seven types CSS Attribute Selectors
AttributeName — Find an element using specific attribute name.
[attributeName]
input[name]
// To narroow it down can use the type like input, button
If it’s very special only we can use this. So , to narrow it down let’s use it with value.
AttributeValue — Find an element using specific attribute value.
[attributeName=attributeValue]
input[placeholder='First Name']
// To narroow it down can use the type like input, button then match the value
AttributeValue-PartialText-WholeWord — If there a sentence as Hi Hello world , you can pass one of thiose whole words.
Here instead of = sign, has to use both~=
[attributeName~=attributeValueWoleword]
input[placeholder~='Enter']
// To narroow it down can use the type like input, button then match the value
AttributeValue-PartialText-Text — can pass partial text like Hell
Here instead of = sign, has to use both*=
[attributeName~=attributePartialeword]
input[placeholder*='Ente']
// To narroow it down can use the type like input, button then match the value
AttributeValue-StartsWith-WholeWord — Start with full word so give Hello
This splits the words using — symbol or whole word.
Here instead of = sign, has to use both |=
To enter | sign use, shift and \
[attributeName~|=StartWIthWholeWorld]
p[class|='my']
AttributeValue-StartsWith-Text Start with partial text of attribute
Here instead of = sign, has to use both ^=
[attributeName~^=StartWIthPartialText]
p[class^='my']
AttributeValue-EndWith-Text Ends with partial text of attribute
Here instead of = sign, has to use both $=
[attributeName~$=StartWIthPartialText]
p[class$='eader']
HTML elements