-1

How can I target elements like this jQuery selector, but without using jQuery?

var header_elements = $("[data-automationid=SiteHeader]");

Explanation: I want to target the element that has a data-autonmationid attribute with the value of SiteHeader

Glenn Ferrie
  • 10,290
  • 3
  • 42
  • 73
  • 2
    `document.querySelectorAll('[data-automationid=SiteHeader]');` – ABC Feb 09 '21 at 19:56
  • 1
    Someone else downvoted, been answered. My result by the way will return an array since you stated header element's, plural. – ABC Feb 09 '21 at 19:58
  • 2
    @File — `querySelectorAll` returns a NodeList, not an array. – Quentin Feb 09 '21 at 20:00
  • 1
    If you wish to target the element using CSS3 here is a whole artical on it... as per the website there are 7 way to handle this based on the complexity https://css-tricks.com/almanac/selectors/a/attribute/#the-seven-different-types – Nishant S Vispute Feb 09 '21 at 20:00
  • @Quentin Correct, which may be accessed by indexes. My bad. – ABC Feb 09 '21 at 21:41

2 Answers2

3

Simply use document.querySelector() for one result or document.querySelectorAll() for a NodeList result.

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

document.querySelector('[data-attr=this]').style.backgroundColor = 'red';
<div>not this one</div>
<div data-attr="this">this one</div>
Giovane
  • 1,421
  • 1
  • 15
  • 25
1

You can select it by

const header_elements = document.querySelectorAll('[data-automationid="SiteHeader"]');

document.querySelector => one element

document.querySelectorAll => multiple elements as NodeList

Paul Facklam
  • 1,623
  • 12
  • 16