1

Is there a way to select all entities with a particular component attached?

I was trying document.querySelectorAll(".shadow"); and various other combinations to no avail.

halfer
  • 18,701
  • 13
  • 79
  • 158

2 Answers2

2

I believe you're looking for a attribute selector - which allows grabbing HTML nodes by their attributes. a-frame components are pretty much custom made HTML attributes - you're setting them using setAttribute() :)

In your case it would be document.querySelectorAll("[shadow]")

Check it out in this fiddle.

Piotr Adam Milewski
  • 10,602
  • 2
  • 18
  • 36
0

Quoting this answer:

That said, the Selectors Level 4 Working Draft includes a :has() pseudo-class that will provide this capability. It will be similar to the jQuery implementation.

li:has(> a.active) { /* styles to apply to the li tag */ } However, as of 2020, this is still not supported by any browser.

In the meantime, you'll have to resort to JavaScript if you need to select a parent element.

In short, there is no querySelectorAll to do this for you.

To do this, you need to select all children with class shadow, then select all their parents like so:

var children = document.querySelectorAll(".shadow");
var parents = [];

children.forEach(child => {
  parents.push(child.parentElement);
})

console.log(parents);
<div class="parent1">
  <div class="shadow"></div>
</div>
<div class="parent2">
  <div class="shadow"></div>
</div>

An article on the limits of CSS selectors

barhatsor
  • 1,347
  • 3
  • 17
  • I'm not sure if components are registered in the same way as classes because querySelectorAll(".shadow") returns empty - I have just added an empty made up class and was able to select using that - seems a bit hacky though – heroicsatsuma Oct 26 '20 at 09:54
  • Yes, I know. In a real environment you would do something like `querySelectorAll("a-image")` etc. Seems hacky, but there is no way to do this with CSS (`querySelector` is in effect just a CSS selector). See this question: https://stackoverflow.com/questions/1014861/is-there-a-css-parent-selector – barhatsor Oct 26 '20 at 09:58
  • I changed the answer above ^ – barhatsor Oct 26 '20 at 09:58