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.

2 Answers 2

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.

1
  • 1
    Thanks @Piotr that's the one I was looking for much appreciated Commented Oct 26, 2020 at 18:20
1

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

3
  • 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 Commented Oct 26, 2020 at 9: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: stackoverflow.com/questions/1014861/…
    – benhatsor
    Commented Oct 26, 2020 at 9:58
  • I changed the answer above ^
    – benhatsor
    Commented Oct 26, 2020 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.