Как найти дата атрибут js

In this article, we’ll discuss how you can get HTML5 data attributes with JavaScript. We’ll go through a couple of real-world examples to demonstrate how you can use these data attributes with vanilla JavaScript and jQuery.

JavaScript is one of the core technologies of the web. The majority of websites use it, and all modern web browsers support it without the need for plugins. In this series, we’re discussing tips and tricks that will help you in your day-to-day JavaScript development.

More often than not, you need to store a bit of extra information along with the different HTML elements on your web app or site. It may not make any sense to users, but it can be helpful to you should you wish to perform operations based on that information.

For example, if you have an HTML table with rows from a database, for each row you might want to store the corresponding database id. That will make edits and other transactions much easier. This is a great use of a custom data attribute.

Until the introduction of these custom data attributes, developers would often use the class attribute to store such information, but the class attribute isn’t actually meant for that, and this practice can make it more complicated to understand the code and the site markup.

With the introduction of HTML5 custom data attributes, it’s really easy to store and retrieve custom data within your HTML.

Access Data Attributes With Vanilla JavaScript

In this section, we’ll discuss different ways that you can use vanilla JavaScript to get HTML5 data attributes.

The HTMLElement.dataset Property

The dataset property allows you to access the data attributes of an element easily.

Let’s consider the following example.

First of all, we’ve defined the data-employee-id custom data attribute on each <li> element, which is used to store the employee ID. It can be used later on to fetch more details of an employee if it’s needed. Next, we’ve defined the onclick event handler on each <li> element, so when you click on any row, it will call the getEmpId function, which eventually fetches the value of the employee-id data attribute associated with the corresponding <li> element.

In the getEmpId function, we’ve used the dataset property of the <li> element which is passed as the first argument. The dataset property returns a DOMStringMap object, which you can use to get individual properties.

When you’re fetching individual properties with the dataset property, there are a few important things. The data- prefix is removed from the attribute name. Any lowercase character followed by a hyphen is converted to uppercase, and the hyphen is removed. In other words, dash-style attribute names are converted to camelCase object keys. Other characters will remain unchanged.

In our case, with these rules, the data-employee-id attribute is converted to employeeId. Thus, you can use element.dataset.employeeId to fetch the value of the data-employee-id attribute.

So that’s how the dataset properly works in vanilla JavaScript.

The getAttribute() Method

In this section, we’ll discuss how you can use the getAttribute method to get the value of data attributes.

We’ll revise the example we discussed in the previous section.

As you can see, it’s pretty straightforward to get custom data attributes with the getAttribute method of an HTML element. You just need to pass the whole attribute name along with the data- prefix to get the value of an attribute.

Access Data Attributes With the jQuery Library

In this section, we’ll discuss how you can use the jQuery library to get HTML5 data attributes.

The data() Method

The jQuery data method allows you to fetch data attributes of an element easily.

Let’s go through the following example to understand how the jQuery data method works.

As you can see, we just need to pass the camel-case version of the data attribute name to get its value.

The attr() Method

In jQuery, you can also use the attr method to get the value of the specific attribute of an element.

Let’s quickly see how you can use the attr method in jQuery.

1

2

3
var empId = $(element).attr('data-employee-id');
4

5

As you can see, the attr method works in the same way as that of the getAttribute method in vanilla JavaScript.

In jQuery, the difference between the data and attr method is that the data method internally converts the string obtained from a data attribute to corresponding types like numbers, booleans, and so on.

So that’s how you can use jQuery to fetch data attributes easily.

Conclusion

Today, we discussed how you can get HTML5 data attributes with JavaScript. With the help of a couple of real-world examples, you learned how HTML5 data attributes work with both vanilla JavaScript and the jQuery library.

Did you find this post useful?

Sajal Soni

Software Engineer, FSPL, India

I’m a software engineer by profession, and I’ve done my engineering in computer science. It’s been around 14 years I’ve been working in the field of website development and open-source technologies.

Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I’ve worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I’ve also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce.

I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music!

One of the best ways to store data in HTML is with data attributes. These data attributes can be used to do some pretty cool things in CSS without the need for JavaScript, as seen in this article, but data attributes are most useful when combined with JavaScript. In this article I will teach you exactly how to use data attributes in JavaScript and what makes them so powerful.

Data Attribute Introduction

To get started talking about data attributes we need to first have some HTML with data attributes. To create a data attribute in HTML we just need to add a custom attribute to our HTML element that starts with data-.

Reading Data Attributes

We now have a div with three custom data attributes. Now let’s move over to JavaScript to see how we would access these data attributes.

The dataset property on an element will return a DOMStringMap which is essentially just an object that contains all the custom data attributes of an element. Our dataset looks like this.

You will notice two interesting things about this.

First, all of our properties are converted from snake case, first-name, to camel case, firstName. This is because in JavaScript object properties are primarily written as camel case so this just makes working with the JavaScript object much easier.

Second, the active property has a value of "". This is because any data attribute without a value is assumed to have an empty string as its value.

Now in order to access an individual data attribute we just access it like a property on an object since dataset is just an object.

Writing Data Attributes

In order to create a new data attribute in JavaScript we just need to add a new property to the dataset object with a value.

This will update the dataset object and our HTML which means our HTML will look like this.

Updating Data Attributes

Let’s say that we now want to update the value of a data attribute. This is incredibly easy since it works just like a normal object. We just need to set the value of our dataset property to the new value and it will update the HTML for us.

This will update the dataset object and our HTML which means our HTML will look like this.

Delete Data Attributes

Deleting data attributes is a bit different since we need to actually remove the property from our object. This is because if we try setting the value to undefined or null the dataset object will still have a reference to that property with that value of undefined or null and will set the value of our HTML data attribute to the string null or undefined.

To delete an element we need to use the delete keyword to remove it completely from the object.

This will update the dataset object and our HTML which means our HTML will look like this.

Real World Example

Now let’s combine all this into a real world example. Let’s say you have the following HTML.

You want to write JavaScript so that the first button opens modal 1 and the second button opens modal 2, but we want to do this in a way that is reusable so if we add a third button that opens a new modal we don’t need to write any new JavaScript code.

This may sound really difficult at first, but essentially all we need is some way to link each button to their respective modal in the HTML. This is where data attributes come in.

We can set a custom data attribute on each button that references the modal they are linked to. In our case we can use the id of each modal as our reference.

So now we have a way to access the id of the modal linked to each button inside JavaScript.

In the above code we are selecting all elements that contain our custom data-modal-id attribute. We are then looping through them and adding a click event listener to each one. Inside this event listener we are using the modal id to get the modal link to that button and adding the show class so it is now visible.

This code is also flexible since it will get any element with the custom data-modal-id attribute. This means that if we add a new button that references a new modal we won’t need to write any additional JavaScript.

Conclusion

Data attributes in JavaScript are incredibly useful. They allow you to write extremely flexible code which means you can spend more time writing the HTML for your project and less time worrying about writing a custom event listener for each new element you add.

Today, we’re going to look at how to get, set, remove, and check for data attributes on an element. Let’s dig in!

What is a data attribute?

A data attribute is a custom attribute on an element that starts with data-*. It can be used to store information (or “state”) about the element, or even just as a selector for JavaScript components.

In this example, the button has a data attribute named [data-click]. It has a value of count.

<button data-click="count">Count Up</button>

Data attributes don’t have to have values, though. In this example, the button has a data attibute of [data-count], without a value.

<button data-count>Count Up</button>

Now, let’s look at how to manipulate them with vanilla JavaScript.

Manipulating data attributes with JavaScript

The Element.getAttribute(), Element.setAttribute(), Element.removeAttribute(), and Element.hasAttribute() methods are used to get, set, remove, and check for the existence of attributes (including data attributes) on an element.

If an attribute does not exist on an element, the Element.getAttribute() method returns null.

let btn = document.querySelector('button');

// Get the value of the [data-click] attribute
// returns "count"
let click = btn.getAttribute('data-click');

// Set a value for the [data-count] attribute
// <button data-count="up">Count Up</button>
btn.setAttribute('data-count', 'up');

// Remove the [data-click] attribute
btn.removeAttribute('data-click');

// Check if an element has the `[data-toggle]` attribute
if (btn.hasAttribute('data-toggle')) {
	console.log('Toggle something, dude!');
}

Data attributes and CSS

Data attributes are also valid CSS selectors. Wrap attribute selectors in square brackets, like this.

/**
 * Style the [data-count] button
 */
[data-count] {
	background-color: #0088cc;
	border-color: #0088cc;
	color: #ffffff;
}

You can also use with JavaScript methods that accept CSS selectors as an argument, like document.querySelector(), document.querySelectorAll(), Element.matches(), and Element.closet().

// Get elements with a data attribute
let count = document.querySelector('[data-count]');
let allCounts = document.querySelectorAll('[data-count]');

// Check if an element has a data attribute
if (count.matches('[data-click]')) {
	console.log('We have a match!');
}

There are some advanced ways to target data attributes, too.

Custom attributes

While data attributes (starting with data-*) are a common convention, you can create custom attributes, too. Some libraries do this.

For example, Vue does this with v-* attributes.

<div id="app-3">
	<span v-if="seen">Now you see me</span>
</div>

You can use the Element.*Attribute() methods to manipulate custom attributes as well.

let span = document.querySelector('[v-if]');

// Update the value of the [v-if] attribute
span.setAttribute('v-if', 'invisible');

Tomorrow, we’ll look at another way to get and set data attributes: the Element.dataset property. And on Friday, we’ll explore different strategies for working with data attributes.

I have next html:

<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>

Is it possible to get the attributes that beginning with data-, and use it in the JavaScript code like code below? For now I get null as result.

document.getElementById("the-span").addEventListener("click", function(){
    var json = JSON.stringify({
        id: parseInt(this.typeId),
        subject: this.datatype,
        points: parseInt(this.points),
        user: "H. Pauwelyn"
    });
});

asked Nov 17, 2015 at 15:19

H. Pauwelyn's user avatar

H. PauwelynH. Pauwelyn

13.4k26 gold badges78 silver badges144 bronze badges

1

You need to access the dataset property:

document.getElementById("the-span").addEventListener("click", function() {
  var json = JSON.stringify({
    id: parseInt(this.dataset.typeid),
    subject: this.dataset.type,
    points: parseInt(this.dataset.points),
    user: "Luïs"
  });
});

Result:

// json would equal:
{ "id": 123, "subject": "topic", "points": -1, "user": "Luïs" }

answered Nov 17, 2015 at 15:21

Josh Crozier's user avatar

Josh CrozierJosh Crozier

231k56 gold badges389 silver badges303 bronze badges

2

Because the dataset property wasn’t supported by Internet Explorer until version 11, you may want to use getAttribute() instead:

document.getElementById("the-span").addEventListener("click", function(){
  console.log(this.getAttribute('data-type'));
});

Dataset documentation

getAttribute documentation

answered Nov 17, 2015 at 15:26

MarkPlewis's user avatar

MarkPlewisMarkPlewis

2,2901 gold badge15 silver badges13 bronze badges

0

You can access it as

element.dataset.points

etc. So in this case: this.dataset.points

answered Nov 17, 2015 at 15:21

meskobalazs's user avatar

meskobalazsmeskobalazs

15.7k2 gold badges40 silver badges62 bronze badges

You could also grab the attributes with the getAttribute() method which will return the value of a specific HTML attribute.

const elem = document.getElementById('the-span');

const typeId = elem.getAttribute('data-typeId');
const type   = elem.getAttribute('data-type');
const points = elem.getAttribute('data-points');
const important = elem.getAttribute('data-important');

console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`
);
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>

answered Nov 11, 2019 at 19:23

ii iml0sto1's user avatar

ii iml0sto1ii iml0sto1

1,59517 silver badges37 bronze badges

if you are targeting data attribute in Html element,

document.dataset will not work

you should use

document.querySelector("html").dataset.pbUserId

or

document.getElementsByTagName("html")[0].dataset.pbUserId

answered Nov 20, 2018 at 8:50

Basheer AL-MOMANI's user avatar

Modern browsers accepts HTML and SVG DOMnode.dataset

Using pure Javascript’s DOM-node dataset property.

It is an old Javascript standard for HTML elements (since Chorme 8 and Firefox 6) but new for SVG (since year 2017 with Chorme 55.x and Firefox 51)… It is not a problem for SVG because in nowadays (2019) the version’s usage share is dominated by modern browsers.

The values of dataset’s key-values are pure strings, but a good practice is to adopt JSON string format for non-string datatypes, to parse it by JSON.parse().

Using the dataset property in any context

Code snippet to get and set key-value datasets at HTML and SVG contexts.

console.log("-- GET values --")
var x = document.getElementById('html_example').dataset;
console.log("s:", x.s );
for (var i of JSON.parse(x.list)) console.log("list_i:",i)

var y = document.getElementById('g1').dataset;
console.log("s:", y.s );
for (var i of JSON.parse(y.list)) console.log("list_i:",i)

console.log("-- SET values --");
y.s="BYE!"; y.list="null";
console.log( document.getElementById('svg_example').innerHTML )
<p id="html_example" data-list="[1,2,3]" data-s="Hello123">Hello!</p>
<svg id="svg_example">
  <g id="g1" data-list="[4,5,6]" data-s="Hello456 SVG"></g>
</svg>

answered Aug 17, 2019 at 21:47

Peter Krauss's user avatar

Peter KraussPeter Krauss

13k23 gold badges165 silver badges298 bronze badges

Circa 2019, using jquery, this can be accessed using $('#DOMId').data('typeId') where $('#DOMId') is the jquery selector for your span element.

answered Oct 6, 2019 at 16:11

den232's user avatar

den232den232

6686 silver badges14 bronze badges

Example:

<input data-default-value="Default Value">Name</input>
inputEl.getAttribute("data-default-value")

→ returns: Default Value

H. Pauwelyn's user avatar

H. Pauwelyn

13.4k26 gold badges78 silver badges144 bronze badges

answered Feb 20 at 15:38

SomeOne's user avatar

document.getElementById('selectTbl').addEventListener('change', function () {
    $("#selectTbl").val();
    var style = $(this).val() == 1 ? 'block' : 'none';
    document.getElementById('TblAdmin').style.display = style;

    var style = $(this).val() == 2 ? 'block' : 'none';
    document.getElementById('TblMech').style.display = style;

    var style = $(this).val() == 3 ? 'block' : 'none';
    document.getElementById('TblUser').style.display = style;

    var style = $(this).val() == 4 ? 'block' : 'none';
    document.getElementById('TblBiz').style.display = style;
});

Sorry to interrupt I think you already got the answer. Can someone help for me?
Here I want to display the div which is TblAdmin, TblMech, TblUser, TblBiz. I’m currently using NiceSelect but inside the select dropdown it has data value attribute. It actually not select but list-item inside unordered-list.

Like picture shown here,
https://drive.google.com/file/d/1VyHDMb1Gl4PYBe19XZt1Z8Z-2OLAS1mx/view?usp=sharing

answered Apr 25, 2022 at 15:47

Adamakmar's user avatar

2

Try this instead of your code:

var type=$("#the-span").attr("data-type");
alert(type);

H. Pauwelyn's user avatar

H. Pauwelyn

13.4k26 gold badges78 silver badges144 bronze badges

answered Nov 17, 2015 at 16:05

Akash Agrawal's user avatar

3

You can actually use JQuery to accomplish that in a very easy way

$(document).on('click', '.the-span', function(){

let type = $(this).data("type");

});

answered Aug 5, 2021 at 21:55

iamnonso's user avatar

iamnonsoiamnonso

1051 silver badge4 bronze badges

1

Работа с data атрибутами в HTML/CSS/JS

Все атрибуты у HTML элементов, начинающиеся с префикса data-*, являются пользовательскими. Data атрибуты можно использовать для дополнительной стилизации, но чаще всего они применяются для создания интерактивной логики в JavaScript. Особенно их любят применять разные библиотеки, когда пользователю предлагается настроить скрипт через data атрибуты. Сделать это может любой начинающий вебмастер с начальным уровнем знаний JavaScript.

Использование data атрибутов в HTML и CSS

Data атрибут – это очень гибкий инструмент и сейчас мы рассмотрим, как можно его использовать в HTML и CSS.

Как добавить data атрибут к HTML тегу

Вначале обязательно ставим префикс data, затем через дефис указываем какое-то наше слово подходящее по смыслу и само значение. Например мы хотим отсортировать только категорию с домашними питомцами. Все слова, за исключением самого префикса data-*, мы можем придумывать свои собственные. Так мы можем управлять отдельными группами элементов, помеченные data атрибутами. Это удобно для создания интерактива на языке JavaScript.


<button data-categories="pets">Pets</button>

Длина названия data атрибута может быть любой, слова должны разделяться через дефис.


<div data-is-active-color="red"></div>

Пример стилизации элементов с data атрибутом

Мы можем стилизовать любой элемент по его data атрибуту. В CSS коде селектор data атрибута заключается в квадратные скобки. Обращаться можно только по названию атрибута, по тегу + название или по классу (id) + название.


// HTML код
<div class="large_btn" data-size="large">button</div>

// CSS код
// селектор по названию атрибута
[data-size="large"] {
    font-size: 30px;
    padding: 20px;
}

// селектор по тегу и названию
div [data-size="large"] {
    font-size: 30px;
    padding: 20px;
}

// селектор по классу и названию
large_btn.[data-size="large"] {
    font-size: 30px;
    padding: 20px;
}


Принцип создания подсказок с data атрибутом на CSS

Прописываем текст подсказки в data атрибуте тега. Затем с помощью псевдоэлементов ::before или ::after передать в функцию attr значение атрибута data-tooltip.


<span data-tooltip="текст подсказки"></span>

[data-tooltip]::after {
    content: attr(data-tooltip);
}


Использование data атрибутов в JavaScript

В JS существует, как минимум два способа получения data атрибута:

Первый способ, через getAttribute и setAttribute

Указываем выбранный на странице элемент (тег, id, класс), сам метод getAttribute и название атрибута, который надо получить.


element.getAttribute("data-filter")

Метод setAttribute добавляет значение, указанное вторым параметром (“pillows”) в data атрибут в первом параметре (“data-filter”).


element.setAttribute("data-filter", "pillows")

Второй способ, через объект dataset в структуре DOM

Доступ к коллекции dataset мы получаем по ключу (слово после префикса data-*).


<div data-person></div>

// Получение data атрибута
div.dataset.person

// Добавление значения для data атрибута
div.dataset.person = "Donald"

Работа с data атрибутами в JavaScript – достаточно актуальная тема, с которой вы будете часто встречаться, более основательно познакомиться с data атрибутами и не только, вы сможете в моем видеокурсе по JavaScript.

Итоги

Data атрибуты позволяют хранить разную информацию об элементе, которая может помочь для работы скриптов, а также для CSS стилизации элементов. HTML код с созданными атрибутами с data-* префиксом будет, абсолютно валидным. Создавать свои собственные data атрибуты для хранения значений стало возможным лишь в HTML5, до этого такой возможности очень не хватало веб-разработчикам. Вот список самых востребованные задач, которые удобно решать с помощью data атрибутов:

  • Создание всплывающих подсказок на чистом CSS
  • Получать и изменять значения атрибутов
  • Создано 16.11.2020 10:06:02


  • Михаил Русаков

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

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

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

  1. Кнопка:

    Она выглядит вот так: Как создать свой сайт

  2. Текстовая ссылка:

    Она выглядит вот так: Как создать свой сайт

  3. BB-код ссылки для форумов (например, можете поставить её в подписи):

Добавить комментарий