Css selector data value

Полное руководство по data атрибутам

Элементы HTML могут иметь атрибуты, которые используются для чего угодно, от информации о доступности до стилистического контроля.

Что не рекомендуется это составление собственных атрибутов или перепрофилирования существующих атрибутов для несвязанного функциональности.

Есть множество причин, по которым это плохо. Ваш HTML-код становится невалидным, что может не иметь никаких реальных негативных последствий, но лишает вас этого теплого нечеткого действительного чувства HTML. Самая веская причина в том, что HTML — это живой язык, и только потому, что атрибуты и значения, которые ничего не делают сегодня, не означают, что они никогда этого не сделают.

Хорошая новость: вы можете создать свои собственные атрибуты. Вам просто нужно добавить к ним префикс, data-* и тогда вы сможете делать то, что вам нравится!

Синтаксис

Может быть очень удобно иметь возможность создавать свои собственные атрибуты HTML и помещать в них свою собственную информацию. К счастью, вы можете это сделать с data атрибутами:

Атрибуты данных часто называют data-* атрибутами, так как они всегда отформатированы таким образом: слово data , затем тире — , затем другой текст, который вы можете составить.

Можете ли вы использовать один атрибут data?

Вероятно, это не повредит, но вы не получите JavaScript API, о котором мы расскажем позже в этом руководстве. По сути, вы создаете для себя атрибут, который, как я уже упоминал во вступлении, не рекомендуется.

Читайте также:  Взвешенный ориентированный граф python

Что не стоит делать с data атрибутами

Хранить контент, который должен быть доступен. Если контент должен просматриваться или читаться на странице, помещайте его не только в data атрибут, но и в HTML-контент.

Стилизация с атрибутами данных

CSS может выбирать элементы HTML на основе атрибутов и их значений.

/* Select any element with this data attribute and value */ [data-size="large"] < padding: 2rem; font-size: 125%; >/* You can scope it to an element or class or anything else */ button[data-type="download"] < >.card[data-pad="extra"]

Это может быть убедительным. Преобладающими хуками стилей в HTML / CSS являются классы, и хотя классы хороши (они имеют среднюю специфичность и хорошие методы JavaScript через classList ), у элемента либо есть, либо нет (по сути, он включен или выключен ). С data-* атрибутами вы получаете эту способность включения / выключения плюс возможность выбирать на основе значения, которое оно имеет на том же уровне специфичности.

/* Selects if the attribute is present at all */ [data-size] < >/* Selects if the attribute has a particular value */ [data-state="open"], [aria-expanded="true"] < >/* "Starts with" selector, meaning this would match "3" or anything starting with 3, like "3.14" */ [data-version^="3"] < >/* "Contains" meaning if the value has the string anywhere inside it */ [data-company*="google"]

Специфика выбора атрибутов

Это точно так же, как класс. Мы часто думаем о специфике как о значении из четырех частей:

встроенный стиль, идентификаторы, классы / атрибуты, теги

Таким образом, один селектор атрибута равен 0, 0, 1, 0. Данный селектор:

2 — потому что есть один class ( .card ) и один attribute ( [data-foo=»bar»] ), а 1 — потому что есть один tag ( div ).

Селекторы атрибутов имеют меньшую специфичность, чем идентификатор, больше, чем элемент / тег, и такие же, как класс.

Значения атрибутов без учета регистра

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

/* Will match */ [data-state="open" i]

Использование атрибутов данных для визуализации

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

Пример использования стиля

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

Доступ к атрибутам данных в JavaScript

Как и любой другой атрибут, вы можете получить доступ к значению с помощью универсального метода getAttribute .

let value = el.getAttribute("data-state"); // You can set the value as well. // Returns data-state="collapsed" el.setAttribute("data-state", "collapsed"); 

Но атрибуты данных также имеют свой собственный API. Допустим, у вас есть элемент с несколькими атрибутами данных (что вполне нормально):

Если у вас есть ссылка на этот элемент, вы можете установить и получить такие атрибуты, как:

// Get span.dataset.info; // 123 span.dataset.index; // 2 // Set span.dataset.prefix = "Mr. "; span.dataset.emojiIcon = "🎪"; 

Обратите внимание на использование camelCase в последней строке. Он автоматически преобразует атрибуты стиля kebab в HTML, например data-this-little-piggy , в стиль camelCase в JavaScript будет dataThisLittlePiggy .

Этот API, возможно, не так хорошо , как classList с четкими методами add , remove , toggle и replace , но это лучше, чем ничего.

У вас также есть доступ к встроенным наборам данных:

Данные JSON внутри атрибутов данных

Эй, а почему бы и нет? Это просто строка, и ее можно отформатировать как допустимый JSON (обратите внимание на кавычки и тому подобное). Вы можете восстановить эти данные и проанализировать их при необходимости.

const el = document.querySelector("li"); let json = el.dataset.person; let data = JSON.parse(json); console.log(data.name); // Chris Coyier console.log(data.job); // Web Person 

Сценарии использования JavaScript

Концепция заключается в том, что вы можете использовать атрибуты данных для помещения в HTML информации, которая может понадобиться JavaScript для выполнения определенных задач.

Обычный пример связан с функциональностью базы данных. Скажем, у вас есть кнопка «Like»:

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

Источник

A Complete Guide to Data Attributes

HTML elements can have attributes on them that are used for anything from accessibility information to stylistic control.

What is discouraged is making up your own attributes, or repurposing existing attributes for unrelated functionality.

There are a variety of reasons this is bad. Your HTML becomes invalid, which may not have any actual negative consequences, but robs you of that warm fuzzy valid HTML feeling. The most compelling reason is that HTML is a living language and just because attributes and values that don’t do anything today doesn’t mean they never will.

Good news though: you can make up your own attributes. You just need to prefix them with data-* and then you’re free to do what you please!

It can be awfully handy to be able to make up your own HTML attributes and put your own information inside them. Fortunately, you can! That’s exactly what data attributes are. They are like this:

Data attributes are often referred to as data-* attributes, as they are always formatted like that. The word data , then a dash — , then other text you can make up.

Can you use the data attribute alone?

It’s probably not going to hurt anything, but you won’t get the JavaScript API we’ll cover later in this guide. You’re essentially making up an attribute for yourself, which as I mentioned in the intro, is discouraged.

What not to do with data attributes

Store content that should be accessible. If the content should be seen or read on a page, don’t only put them in data attributes, but make sure that content is in the HTML content somewhere.

Styling with data attributes

/* Select any element with this data attribute and value */ [data-size="large"] < padding: 2rem; font-size: 125%; >/* You can scope it to an element or class or anything else */ button[data-type="download"] < >.card[data-pad="extra"]

This can be compelling. The predominant styling hooks in HTML/CSS are classes, and while classes are great (they have medium specificity and nice JavaScript methods via classList ) an element either has it or it doesn’t (essentially on or off). With data-* attributes, you get that on/off ability plus the ability to select based on the value it has at the same specificity level.

/* Selects if the attribute is present at all */ [data-size] < >/* Selects if the attribute has a particular value */ [data-state="open"], [aria-expanded="true"] < >/* "Starts with" selector, meaning this would match "3" or anything starting with 3, like "3.14" */ [data-version^="3"] < >/* "Contains" meaning if the value has the string anywhere inside it */ [data-company*="google"]

The specificity of attribute selectors

It’s the exact same as a class. We often think of specificity as a four-part value:

inline style, IDs, classes/attributes, tags

So a single attribute selector alone is 0, 0, 1, 0. A selector like this:

…would be 0, 0, 2, 1. The 2 is because there is one class ( .card ) and one attribute ( [data-foo=»bar»] ), and the 1 is because there is one tag ( div ).

Illustration of a CSS selector including a data attribute.

Attribute selectors have less specificity than an ID, more than an element/tag, and the same as a class.

Case-insensitive attribute values

In case you’re needing to correct for possible capitalization inconsistencies in your data attributes, the attribute selector has a case-insensitive variant for that.

/* Will match */ [data-state="open" i]

It’s the little i within the bracketed selector.

Using data attributes visually

CSS allows you to yank out the data attribute value and display it if you need to.

You could use data attributes to specify how many columns you want a grid container to have.

Accessing data attributes in JavaScript

Like any other attribute, you can access the value with the generic method getAttribute .

let value = el.getAttribute("data-state"); // You can set the value as well. // Returns data-state="collapsed" el.setAttribute("data-state", "collapsed");

But data attributes have their own special API as well. Say you have an element with multiple data attributes (which is totally fine):

If you have a reference to that element, you can set and get the attributes like:

// Get span.dataset.info; // 123 span.dataset.index; // 2 // Set span.dataset.prefix = "Mr. "; span.dataset.emojiIcon = "🎪";

Note the camelCase usage on the last line there. It automatically converts kebab-style attributes in HTML, like data-this-little-piggy , to camelCase style in JavaScript, like dataThisLittlePiggy .

This API is arguably not quite as nice as classList with the clear add , remove , toggle , and replace methods, but it’s better than nothing.

You have access to inline datasets as well:

JSON data inside data attributes

Hey, why not? It’s just a string and it’s possible to format it as valid JSON (mind the quotes and such). You can yank that data and parse it as needed.

const el = document.querySelector("li"); let json = el.dataset.person; let data = JSON.parse(json); console.log(data.name); // Chris Coyier console.log(data.job); // Web Person

The concept is that you can use data attributes to put information in HTML that JavaScript may need access to do certain things.

A common one would have to do with database functionality. Say you have a “Like” button:

That button could have a click handler on it which performs an Ajax request to the server to increment the number of likes in a database on click. It knows which record to update because it gets it from the data attribute.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Mobile / Tablet

Источник

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