Как найти элемент по data атрибуту js

от admin

How to select a element using data attribute in JavaScript

In this tutorial, we are going to learn how to select/access an html element using the data attribute in JavaScript.

Consider, we have html elements with data attributes.

Now, we need to select the above elements by data attribute in JavaScript.

Selecting the Single element

To select the single element, we need to use document.querySelector() method by passing a [data-attribute = ‘value’] as an argument.

Selecting the Multiple elements

To select the multiple elements with the same data attribute name, we need to use the document.querySelectorAll() method by passing a [data-attribute] as an argument.

In the above example, the querySeletorAll() method returns the multiple elements in an array to access each element we need to loop through it.

How to Query Elements using Data Attribute in JavaScript

Sometimes it is useful to be able to query for elements in the DOM using their data attributes.

Data attributes are a way to associate data with elements in the DOM. Any attribute that starts with a data- prefix is considered a data attribute.

In this post, we will learn how to query for elements using their data attributes.

Querying for Elements Using Data Attributes

For our example, let’s assume this is our DOM:

Querying a Single Element

Let’s start with the simplest query, getting a single element. We’ll be using docuemnt.querySelector() to do this.

Simply pass in the data attribute name and value as arguments to document.querySelector() and you will get the element:

Querying Multiple Elements

You can go from querying a single element to querying multiple elements.

To do this, we will be using document.querySelectorAll() instead of document.querySelector() .

Let’s try querying all elements with the data-name attribute:

Notice that we get an array of elements back. This means we can loop through the array to get each element.

Here’s how we can use the forEach() method to loop through the array:

You can also use a normal for loop to get all the elements one-by-one:

Conclusion

In this post, we learned how to query for elements using their data attributes.

We can either get single elements using document.querySelector() or multiple elements using document.querySelectorAll() .

Hopefully, this has been useful to you. Happy coding!

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

Как найти элемент по data атрибуту js

In this tutorial, we are going to learn how to select/access an html element using the data attribute in JavaScript.

Consider, we have html elements with data attributes.

Now, we need to select the above elements by data attribute in JavaScript.

Читать:
Как безопасно извлечь жесткий диск

Selecting the Single element

To select the single element, we need to use document.querySelector() method by passing a [data-attribute = ‘value’] as an argument.

Selecting the Multiple elements

To select the multiple elements with the same data attribute name, we need to use the document.querySelectorAll() method by passing a [data-attribute] as an argument.

In the above example, the querySeletorAll() method returns the multiple elements in an array to access each element we need to loop through it.

javascript: выберите все элементы с атрибутом» data — » (без jQuery)

Select all elements with a «data-xxx» attribute without using jQuery

Using only pure JavaScript, what is the most efficient way to select all DOM elements that have a certain data- attribute (let’s say data-foo ).

The elements may be different, for example:

7 Answers 7

will get you all elements with that attribute.

will only get you ones with a value of 1.

user avatar

to get list of all elements having attribute data-foo

If you want to get element with data attribute which is having some specific value e.g

and I want to get div with data-foo set to «2»

But here comes the twist what if I want to match the data attirubte value with some variable’s value like I want to get element if data-foo attribute is set to i

so you can dynamically select the element having specific data element using template literals

Note even if you don’t write value in string it gets converted to string like if I write

and then inspect the element in Chrome developer tool the element will be shown as below

You can also cross verify by writing below code in console

why I have written ‘dataFoo’ though the attribute is data-foo reason dataset properties are converted to camelCase properties

Выбор элемента по атрибуту данных

Есть ли простой и прямой метод для выбора элементов на основе их атрибута data ? Например, выберите все привязки, у которых есть атрибут данных с именем customerID , который имеет значение 22 .

Я не решаюсь использовать rel или другие атрибуты для хранения такой информации, но мне гораздо труднее выбрать элемент, основанный на том, какие данные хранятся в нем.

11 ответов

Вы можете опустить * , но если я правильно помню, в зависимости от того, какую версию jQuery вы используете, это может дать неверные результаты.

Обратите внимание, что для совместимости с API-интерфейсом Selectors ( document.querySelector <,all>) кавычки вокруг значения атрибута ( 22 ) не могут быть опущены в этом случае.

Кроме того, если вы много работаете с атрибутами данных в сценариях jQuery, вам может потребоваться использовать плагин атрибутов пользовательских данных HTML5. Это позволяет вам писать еще более читаемый код с помощью .dataAttr(‘foo’) и приводит к меньшему размеру файла после минимизации (по сравнению с использованием .attr(‘data-foo’) ).

Похожие статьи