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

How can I select elements with a specific class while excluding those with any additional classes

Suppose, I have three links,

<a class="a b">1</a>
<a class="a">1</a>
<a class="a">1</a>

Now i just want links which only have the class "a". If i use document.querySelectorAll('.a') then i will get all three of the links.

I know i can use document.querySelectorAll('.a:not(.b)'). but for that i need to know all the class name specifically. I just want to get the link which only had the class "a".

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

>Solution :

I would filter the original results by checking the length of the classList.

const withA = [...document.querySelectorAll("a")];
const onlyA = withA.filter(a => a.classList.length == 1);
console.log(onlyA.length);
<a class="a b">1</a>
<a class="a">1</a>
<a class="a">1</a>
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