skip to Main Content

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".

2

Answers


  1. It might be a bit of a hack, but if the goal is to find the exact class value of "a" then you can use an attribute selector:

    document.querySelectorAll('a[class="a"]').forEach(x => x.innerHTML = "2");
    <a class="a b">1</a>
    <a class="a">1</a>
    <a class="a">1</a>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search