Select by attribute value css

[attribute]

There are lots of ways you can select elements in CSS. The most basic selection is by tag name, like p < >. Almost anything more specific than a tag selector uses attributes — class and ID both select on those attributes on HTML elements. But class and ID aren’t the only attributes developers can select. We can use any of an element’s attributes as selectors. Attribute selection has a special syntax. Here’s an example:

That’s an exact match selector that will only select links with the exact href attribute value of “https://css-tricks.com”.

The Seven Different Types

Attribute selectors are case-sensitive by default (see case-insensitive matching below), and are written inside brackets [] . There are seven different types of matches you can find with an attribute selector, and the syntax is different for each. Each of the more complex attribute selectors build on the syntax of the exact match selector — they all start with the attribute name and end with an equals sign followed by the attribute value(s), usually in quotes. What goes between the attribute name and equals sign is what makes the difference among the selectors.

[data-value] < /* Attribute exists */ >[data-value="foo"] < /* Attribute has this exact value */ >[data-value*="foo"] < /* Attribute value contains this value somewhere in it */ >[data-value~="foo"] < /* Attribute has this value in a space-separated list somewhere */ >[data-value^="foo"] < /* Attribute value starts with this */ >[data-value|="foo"] < /* Attribute value starts with this in a dash-separated list */ >[data-value$="foo"] < /* Attribute value ends with this */ >

Value contains: attribute value contains a term as the only value, a value in a list of values, or as part of another value. To use this selector, add an asterisk (*) before the equals sign. For example, img[alt*=»art»] will select images with the alt text “abstract art” and “athlete starting a new sport”, because the value “art” is in the word “starting”. Value is in a space-separated list: value is either the only attribute value, or is a whole value in a space-separated set of values. Unlike the “contains” selector, this selector will not look for the value as a word fragment. To use this selector, add a tilde (~) before the equals sign. For example, img[alt~=»art»] will select images with the alt text “abstract art” and “art show”, but not “athlete starting a new sport” (which the “contains” selector would select). Value starts with: attribute value starts with the selected term. To use this selector, add a caret (^) before the equals sign. Don’t forget, case-sensitivity matters. For example, img[alt^=”art”] will select images with the alt text “art show” and “artistic pattern”, but not an image with the alt text “Arthur Miller” because “Arthur” begins with a capital letter. Value is first in a dash-separated list: This selector is very similar to the “starts with” selector. Here, the selector matches a value that is either the only value or is the first in a dash-separated list of values. To use this selector, add a pipe character (|) before the equals sign. For example, li[data-years|=»1900″] will select list items with a data-years value of “1900-2000”, but not the list item with a data-years value of “1800-1900”. Value ends with: attribute value ends with the selected term. To use this selector, add a dollar sign ($) before the equals sign. For example, a[href$=»pdf»] selects every link that ends with .pdf.

Читайте также:  Таблица основных тегов и атрибутов html

A note about quotes: You can go without quotes around the value in some circumstances, but the rules for selecting without quotes are inconsistent cross-browser. Quotes always work, so if you stick to using them you can be sure your selector will work.

See the Pen Attribute Selectors by CSS-Tricks (@css-tricks) on CodePen. Fun fact: the values are treated as strings, so you don’t have to do any fancy escaping of characters to make them match, as you would if you used unusual characters in a class or ID selector.

Case-insensitive attribute selectors are part of the CSS Working Group’s Selectors Level 4 specification. As mentioned above, attribute value strings are by default case-sensitive, but can be changed to case-insensitive by adding i just before the closing bracket:

Case-insensitive matching could be really handy for targeting attributes holding unpredictable, human-written text. For example, suppose you were styling a speech bubble on a chat app and wanted to add a “waving hand” to any messages with the text “hello” in some form. You could do so with only CSS, using a case-insensitive matcher to catch all possible variations: See the Pen Case-insensitive CSS attribute matching by CSS-Tricks (@css-tricks) on CodePen.

div[attribute="value"] < /* style rules here */ >.module[attribute="value"] < /* style rules here */ >#header[attribute="value"] < /* style rules here */ >

Or even combine multiple attribute selectors. This example selects images with alt text that includes the word “person” as the only value or a value in a space separated list, and a src value that includes the value “lorem”:

Attribute Selectors in JavaScript and jQuery

Attribute selectors can be used in jQuery just like any other CSS selector. In JavaScript, you can use attribute selectors with document.querySelector() and document.querySelectorAll() . See the Pen Attribute Selectors in JS and jQuery by CSS-Tricks (@css-tricks) on CodePen.

Источник

Селектор по атрибуту

Селектор по атрибуту находит элемент на странице по значению либо по наличию атрибута.

Пример

Скопировать ссылку «Пример» Скопировано

   Октябрь уж наступил — уж роща отряхает Последние листы с нагих своих ветвей;  blockquote cite="А. С. Пушкин"> Октябрь уж наступил — уж роща отряхаетbr> Последние листы с нагих своих ветвей; blockquote>      

Селектор ниже найдёт все цитаты ( ) с атрибутом cite :

 blockquote[cite]  background-color: #2E9AFF; color: #000000;> blockquote[cite]  background-color: #2E9AFF; color: #000000; >      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Этот тип селектора помогает нам стилизовать элементы, опираясь либо на наличие самого атрибута, либо на его значение.

После элемента в квадратных скобках указывается атрибут. При выборке по значению дополнительно указывается, что атрибут должен быть равен значению в кавычках.

[attr ]

Скопировать ссылку «[attr]» Скопировано

Селектор выберет все элементы, у которых присутствует атрибут attr .

  button disabled>OKbutton>      
 [disabled]  opacity: 0.5;> [disabled]  opacity: 0.5; >      

[attr = value ] или [attr = «value» ]

Скопировать ссылку «[attr=value] или [attr=»value»]» Скопировано

Селектор выберет все элементы, атрибут attr которых в точности равен value .

Если в значении атрибута есть пробелы или знаки, отличные от цифр и букв, то значение нужно указывать в кавычках. В остальных случаях кавычки не обязательны.

 Пустая ссылка Эта ссылка не стилизуется a href="#">Пустая ссылкаa> a href="#one">Эта ссылка не стилизуетсяa>      
 [href="#"]  color: red;> [href="#"]  color: red; >      

[attr ~ = value ]

Скопировать ссылку «[attr~=value]» Скопировано

Селектор выбирает все элементы, значение атрибута attr это перечень слов, разделённых пробелом, и среди этих слов есть такое, чьё значение равно value .

 
.
.
blockquote cite="Александр Сергеевич Пушкин">. blockquote> blockquote cite="Лев Николаевич Толстой ">. blockquote>
 [cite~="Пушкин"]  border: 1px solid green;> [cite~="Пушкин"]  border: 1px solid green; >      

[attr| = value ]

Скопировать ссылку «[attr|=value]» Скопировано

Селектор выберет все элементы, значение атрибута attr которых либо в точности равно value , либо начинается с value , за которым следует символ дефиса — (U+002D). Подобный вариант селектора чаще всего используется для выбора по коду языка (например en — U S или en — G B ).

 
Hello World!
世界您好!
世界您好!
div lang="en-us en-gb en-au en-nz">Hello World!div> div lang="zh-CN">世界您好!div> div lang="zh-TW">世界您好!div>
 [lang|="en"]  color: blue;> [lang|="en"]  color: blue; >      
 [lang|="zh"]  color: red;> [lang|="zh"]  color: red; >      

[attr^ = value ]

Скопировать ссылку «[attr^=value]» Скопировано

Селектор выберет все элементы, значение атрибута attr которых начинается с value .

 Ссылка по протоколу HTTPSСсылка по протоколу HTTP a href="https://secure.com/">Ссылка по протоколу HTTPSa> a href="http://secure.com/">Ссылка по протоколу HTTPa>      

У ссылок по протоколу HTTPS справа отображается замок:

 [href^="https"]::after  content: "🔐"; margin-left: 3px;> [href^="https"]::after  content: "🔐"; margin-left: 3px; >      

[attr$ = value ]

Скопировать ссылку «[attr$=value]» Скопировано

Селектор выберет все элементы, значение атрибута attr которых оканчивается на value .

 Apple USApple RussiaApple Italy a href="https://apple.com/">Apple USa> a href="https://apple.com/ru">Apple Russiaa> a href="https://apple.com/it">Apple Italya>      
 a::after  content: "🇺🇸";>a[href$="/ru"]::after  content: "🇷🇺";>a[href$="/it"]::after  content: "🇮🇹";> a::after  content: "🇺🇸"; > a[href$="/ru"]::after  content: "🇷🇺"; > a[href$="/it"]::after  content: "🇮🇹"; >      

[attr* = value ]

Скопировать ссылку «[attr*=value]» Скопировано

Селектор выберет все элементы, атрибут attr которых содержит в себе значение value .

  img src="/img/myadvertisingbanner.png"> img src="/img/other-advert-banner.png"> img src="/img/Advert-image.png">      

Спрячет две первых рекламных картинки. Оба изображения в атрибуте src содержат подстроку advert.

 img[src*="advert"]  display: none;> img[src*="advert"]  display: none; >      

Третья картинка не спрячется, потому что не совпал регистр символов. Advert и advert — это разные значения с точки зрения браузера.

[attr operator value i ]

Скопировать ссылку «[attr operator value i]» Скопировано

Если добавить в скобки после значения атрибута i или I , то браузер будет игнорировать регистр символов.

  img src="/img/myadvertisingbanner.png"> img src="/img/other-advert-banner.png"> img src="/img/Advert-image.png">      

Теперь будут спрятаны все три картинки

 img[src*="advert" i]  display: none;> img[src*="advert" i]  display: none; >      

На практике

Скопировать ссылку «На практике» Скопировано

Денис Ежков советует

Скопировать ссылку «Денис Ежков советует» Скопировано

🛠 При помощи селектора по атрибуту круто стилизовать ссылки, основываясь на значении атрибута href . Можно визуально разделять ссылки, ведущие на соседние страницы сайта, и ссылки, ведущие на другие сайты:

 О насДоставкаКонтактыМы на Medium a href="http://mysite.ru/about">О насa> a href="http://mysite.ru/delivery">Доставкаa> a href="http://mysite.ru/contacts">Контактыa> a href="http://medium.com/mysite-blog">Мы на Mediuma>      

Все ссылки будут с иконкой стрелочки:

 [href^="http"]::after  content: ''; display: inline-block; background-image: url(arrow-top-right.svg);> [href^="http"]::after  content: ''; display: inline-block; background-image: url(arrow-top-right.svg); >      

Внутренние ссылки — без иконок:

 [href*="/mysite.ru/"]::after  display: none;> [href*="/mysite.ru/"]::after  display: none; >      

Источник

Оцените статью