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

document.querySelectorAll('[data-foo]')

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

<div data-foo="1"></div>
<div data-foo="2"></div>

and I want to get div with data-foo set to “2”

document.querySelector('[data-foo="2"]')

But here comes the twist … what if I want to match the data attirubte value with some variable’s value? For example, if I want to get the elements where data-foo attribute is set to i

var i=2;

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

document.querySelector(`[data-foo="${i}"]`)

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

<div data-foo=1></div>

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

<div data-foo="1"></div>

You can also cross verify by writing below code in console

console.log(typeof document.querySelector(`[data-foo="${i}"]`).dataset('dataFoo'))

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

I have referred below links:

  • MDN: data-*
  • MDN: Using data attributes

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:

	<div data-id="1" data-name="foo">Foo</div>
<div data-id="2" data-name="bar">Bar</div>
<div data-id="3" data-name="baz">Baz</div>

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:

	const foo = document.querySelector('[data-name="foo"]');

console.log(foo);

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:

	const names = document.querySelectorAll("[data-name]");

console.log(names);

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:

	names.forEach(name => console.log(name));

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

	for (const name of names) {
    console.log(name);
}

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!

  • Support Us

  • Join

  • Share

  • Tweet

  • Share

Give feedback on this page!

Ezoic

I have a list like so

<ul id="a">
<li data-id="i1" data-pk-type="foo bar">sdfsf</li>
<li data-id="i2" data-pk-type="foo">sdfs</li>
<li data-id="i3" data-pk-type="bar baz">sfdsf</li>
<li data-id="i4" data-pk-type="qux foo">sfds</li>
<li data-id="i5" data-pk-type="baz">sdff</li>
</ul>

I want to find all the elements that contain a given data-pk-type. I am trying the following unsuccessful code because .data("pkType", "foo") actually sets the data attribute to foo;

var $links = $("#a").find("li").data("pkType", "foo");

I could do something like

var $links = $("#a").find("li", "[data-pk-type='foo']");

however that wouldn’t work as well… I want any element that might contain foo. Suggestions?

Brian Tompsett - 汤莱恩's user avatar

asked Jan 10, 2012 at 17:55

punkish's user avatar

Description

You should use jQuerys Attribute Contains Selector [name*="value"].

Attribute Contains Selector [name*=”value”]: Selects elements that have the specified attribute with a value containing the a given substring

Check out the sample and jSFiddle Demonstration

Sample

$links = $("li[data-pk-type*='foo']");
alert($links.length);

will give you a 3, so 3 elements was found.

More Information

  • Attribute Contains Selector [name*=”value”]
  • jSFiddle Demonstration

answered Jan 10, 2012 at 18:02

dknaack's user avatar

dknaackdknaack

59.8k27 gold badges151 silver badges201 bronze badges

1

I’ve previously answered a very similar question: jQuery 1.4.4: How to find an element based on its data-attribute value?. (I fancy you may have seen it already, since I got an upvote on it this afternoon.)

Basically, I think you’re using the wrong tool here. data- attributes should be used for storing data that doesn’t logically fit into the normal attributes. In this case, your data-id and data-pk-type logically map to the normal id attribute and to the normal class attribute. This is especially true because you want to find one of a set of space-separated “types” – exactly the same implementation as classes.

Using normal attributes will make your elements much easier and quicker to find.

<ul id="a">
<li id="i1" class="pk-foo pk-bar">sdfsf</li>
<li id="i2" class="pk-foo">sdfs</li>
<li id="i3" class="pk-bar pk-baz">sfdsf</li>
<li id="i4" class="pk-qux pk-foo">sfds</li>
<li id="i5" class="pk-baz">sdff</li>
</ul>

Note that I have “namespaced” the classes with pk-. This may not be necessary depending on how variant and numerous they are.

You can then find the elements with a normal selector:

$('li.pk-foo');

Community's user avatar

answered Jan 10, 2012 at 18:03

lonesomeday's user avatar

lonesomedaylonesomeday

232k50 gold badges314 silver badges317 bronze badges

In Short:

$("#a").find("li[data-pk-type='foo']");

answered Jan 10, 2012 at 17:59

Luc Laverdure's user avatar

Luc LaverdureLuc Laverdure

1,3882 gold badges19 silver badges35 bronze badges

use this $("#a").find("li[data-pk-type='foo']");

for more info read about jquery selectors from here

answered Jan 10, 2012 at 18:02

Dau's user avatar

DauDau

8,4384 gold badges23 silver badges48 bronze badges

Здравствуйте.
Нашел и собрал вот такой код с ошибками (ошибки data-reactid, elem = document.querySelector(#data-reactid); ):

<script>
function chpok(data-reactid){
    elem = document.querySelector(#data-reactid); //находим блок div который нужно как-то передать в функцию по data-reactid
    state = elem.style.display; //смотрим, включен ли сейчас элемент
    if (state =='') elem.style.display='none'; //если включен, то выключаем
    else elem.style.display=''; //иначе - включаем
}
</script>

Он должен работать (т.е. отображать блоки div или скрывать при нажатии на кнопки) для тегов HTML вида:

<button onclick="chpok('.1.$0')">
Вопрос 1
</button>
<div data-reactid='.1.$0' style="display:none">
Это выводится первый вопрос?
</div>
<button onclick="chpok('.1.$1')">
Вопрос 2
</button>
<div data-reactid='.1.$1' style="display:none">
Тут выводится второй вопрос.
</div>

Если везде заменить “data-reactid” на “id”, и ошибочную строку на строку elem = document.getElementById(id); то все работает, но проблема в том, что в тегах на сайте нет и не будет аттрибута id. Подскажите пожалуйста можно ли получить элемент по атрибуту тега вида “data-reactid” – они уникальны для каждого объекта на странице. И что тогда нужно сделать? Заранее спасибо за любой ответ.

Мы можем использовать data- атрибуты для хранения данных в наших HTML-элементах.

Следовательно, мы можем захотеть получить эти элементы и использовать их.

В этой статье мы рассмотрим, как выбрать все элементы с атрибутом data- с помощью стандартного JavaScript.

Выделите все элементы с атрибутом «data- *» с помощью ванильного JavaScript

Мы можем выбрать все элементы с атрибутом data- с помощью метода document.querySelectorAll.

Например, мы можем написать следующий HTML:

<p data-foo='1'>
  1
</p>
<p data-foo='2'>
  2
</p>

Затем мы можем выбрать все элементы с атрибутом data-foo, написав:

const dataFoo = document.querySelectorAll('[data-foo]');
console.log(dataFoo)

Чтобы выбрать элементы с атрибутом data-foo, установленным на заданное значение, мы можем написать:

const dataFoo = document.querySelectorAll('[data-foo="1"]');
console.log(dataFoo)

Затем мы получаем атрибут data-foo со значением, равным 1.

Чтобы получить значение атрибута value из объекта элемента, мы можем использовать свойство dataset.

Например, мы можем написать:

const dataFoo = document.querySelector('[data-foo="1"]');
console.log(dataFoo.dataset.foo)

для выбора элемента с атрибутом data-foo, установленным на 1 с document.querySelector.

Затем мы используем dataFoo.dataset.foo, чтобы получить значение атрибута data-foo из выбранного элемента.

Свойство dataFoo.dataset.foo также является сеттером, поэтому мы можем написать:

const dataFoo = document.querySelector('[data-foo="1"]');
dataFoo.dataset.foo = 3

чтобы заменить значение атрибута data-foo, равное 1, на 3.

Заключение

Мы можем выбрать все элементы с заданным атрибутом data-, установленным с помощью метода document.querySelectorAll с заданным селектором.

Больше контента на plainenglish.io

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