Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.querySelector multiple data-attributes in one element

I'm trying to find an element with document.querySelector which has multiple data-attributes:

<div class="text-right" data-point-id="7febe088-4eca-493b-8455-385b39ad30e3" data-period="current">-</div> 

I thought about something like this:

document.querySelector('[data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"] [data-period="current"]') 

But it does not work.
However, it works well, if I put the second data-attribute in a child-element like:

<div class="text-right" data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"> <span data-period="current">-</span> </div> 

So, is there an option to search for both attributes at once?
I've tried several options but I don't get it.

like image 871
wiesson Avatar asked Apr 29 '15 08:04

wiesson


People also ask

How do I select multiple ids in querySelector?

Use the querySelectorAll() method to select elements by multiple ids, e.g. document. querySelectorAll('#box1, #box2, #box3') . The method takes a string containing one or more selectors as a parameter and returns a collection of the matching elements. Here is the HTML for the examples in this article.

Can you select multiple elements with querySelector?

Yes, because querySelectorAll accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector.

How do I use querySelector with data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document. Here is the HTML for the examples in this article.

Can you use querySelector on an element?

The querySelector() method is available on the document object or any Element object.


1 Answers

There should not be a space between the 2 selectors

document.querySelector('[data-point-id="7febe088-4eca-493b-8455-385b39ad30e3"][data-period="current"]') 

if you give a space between them it will become a descendant selector, ie it will search for an element attribute data-period="current" which is inside an element with data-point-id="7febe088-4eca-493b-8455-385b39ad30e3" like

<div class="text-right" data-point-id="7febe088-4eca-493b-8455-385b39ad30e3">     <div data-period="current">-</div> </div> 
like image 187
Arun P Johny Avatar answered Oct 13 '22 10:10

Arun P Johny