javascriptgetelementsbyclassname

document.getElementsByClassName - How to get elements having ONLY the specified Class - no Secondary or Subclasses


How do I locate ONLY the elements having the class "Cover" but not the elements having more classes than Cover. Using getElementsByClassName I was not able to discover a way for it to NOT also find elements having the "Cover" class and also the "place-holder" class.

Also I question what the correct terminology is for the 2nd class of "place-holder". Do we refer to that class as a subclass or is it simply just a 2nd class on the element?

<div>
    <a class="Cover" href="javascript:void(0);" tabindex="1" aria-label="First Name: firstName" style="height: 38px; left: 26px; width: 1035px; top: 274.375px;"></a>
    <a class="Cover" href="javascript:void(0);" tabindex="2" aria-label="Last Name: lastName" style="height: 38px; left: 26px; width: 1035px; top: 314.375px;"></a>
    <a class="Cover" href="javascript:void(0);" tabindex="3" aria-label="Suffix: Suffix" style="height: 38px; left: 26px; width: 1035px; top: 354.375px;"></a>
    <a class="Cover place-holder" href="javascript:void(0);" tabindex="10" style="height: 34px; left: 26px; width: 1035px; top: 634.375px;"></a>
    <a class="Cover" href="javascript:void(0);" tabindex="20" aria-label="Gender: Gender" style="height: 108px; left: 26px; width: 1035px; top: 1619.75px;"></a>
</div>

Simple Javascript:

document.getElementsByClassName("Cover");

// finds five elements.  How do I tell it to find ONLY elements having the Cover Class?

Solution

  • simply:

    const onlyCover = document.querySelectorAll('[class="Cover"]');
    
    onlyCover.forEach( elm =>
      {
      console.log( elm.className, elm.textContent );
      })
    <div>
      <a href="#" class="Cover" >aa</a>
      <a href="#" class="Cover" >bb</a>
      <a href="#" class="Cover" >cc</a>
      <a href="#" class="Cover place-holder" >dd</a>
      <a href="#" class="Cover" >ee</a>
    </div>