代码之家  ›  专栏  ›  技术社区  ›  Code Novice

document.getElementsByClassName-如何获取只有指定类的元素-没有辅助类或子类

  •  1
  • Code Novice  · 技术社区  · 3 年前

    如何仅定位类为“Cover”的元素,而不定位类多于Cover的元素。使用getElementsByClassName,我无法找到一种方法,使其不同时查找具有“Cover”类和“placeholder”类的元素。

    此外,我还质疑第二类“占位符”的正确术语是什么。我们是将该类称为子类,还是仅仅是元素上的第二个类?

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

    简单的Javascript:

    document.getElementsByClassName("Cover");
    
    // finds five elements.  How do I tell it to find ONLY elements having the Cover Class?
    
    2 回复  |  直到 3 年前
        1
  •  2
  •   Mister Jojo Łukasz Daniel Mastalerz    3 年前

    简单地说:

    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>
        2
  •  2
  •   Andrew Parks    3 年前

    let elems = [...document.getElementsByClassName('Cover')]
      .filter(i=>i.classList.length===1)
      
    console.log(elems)
    <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>