Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript querySelector – Select elements when the tag ends in a specified string

I am getting started with Web Components and want to get all elements where the tag name ends in "-component", in order to register them as custom tags.

For best performance, I want to use querySelectorAll and not iterate over all elements.

However, as you can see in the following example [tag$="-component"] does not find the elements.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const components = document.querySelectorAll('[tag$="-component"]');
const result = document.querySelector('.result');

result.innerHTML = 'Search started<br>';

for(var i = 0; i < components.length; i++){
 
  result.innerHTML = result.innerHTML + components[i].tagName + '<br>';
 
}
<my-component>

  <hello-world-component>
  
    <h1>Hello, world!</h1>
  
  </hello-world-component>

</my-component>

<div class="result"></div>

If anyone knows what is going on and could let me know or if anyone knows if this is even possible it would be greatly appreciated.

>Solution :

The CSS syntax $= applies to element attributes, not to elements themselves.

There is no syntax to create a CSS selector that matches elements that have a certain suffix.

However, if the purpose is to find custom elements that have not been registered yet, you can use the :defined selector:

const components = document.querySelectorAll(':not(:defined)');
const result = document.querySelector('.result');

result.innerHTML = 'Search started<br>';

for(var i = 0; i < components.length; i++){
  result.innerHTML = result.innerHTML + components[i].tagName + '<br>';
}
<my-component>
  <hello-world-component>
    <h1>Hello, world!</h1>
  </hello-world-component>
</my-component>
<div class="result"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading