This question already has answers here:
Best way to find DOM elements with css selectors
                                
                                    (5个答案)
                                
                        
                                去年关闭。
            
                    
所以我有这个CSS:

tag[class*="samepart-"] {
  /* css code for all html classes with "samepart-" in their class name */
}


与此HTML:

<div class="samepart-a">some html a</div>
<div class="samepart-b">some html b</div>
<div class="samepart-c">some html c</div>


现在,我想在JS中获得所有带有“ samepart-”的html类,而不必在“ samepart-”类中添加额外的html类。

这是我尝试的:



const htmlClasses1 = document.getElementsByClassName("samepart-");
console.log(htmlClasses1[0]);

const htmlClasses2 = document.getElementsByClassName('*["samepart-"]');
console.log(htmlClasses2[0]);

const htmlClasses3 = document.getElementsByClassName('[class*="samepart-"]');
console.log(htmlClasses3[0]);

const htmlClasses4 = document.getElementsByClassName(["samepart-"]);
console.log(htmlClasses4[0]);

div[class*="samepart-"] {
  display: inline-block;
  width: 120px;
  height: 120px;
  background-color: #00F;
  color: #0FF;
}

<div class="samepart-a">some html a</div>
<div class="samepart-b">some html b</div>
<div class="samepart-c">some html c</div>

最佳答案

使用querySelectorAll()

PS:我将*=编辑为^=,因为看来您只想要以samepart开头的类。



const htmlClasses = document.querySelectorAll("div[class^='samepart-']");
console.log(htmlClasses);

div[class*="samepart-"] {
  display: inline-block;
  width: 120px;
  height: 120px;
  background-color: #00F;
  color: #0FF;
}

<div class="samepart-a">some html a</div>
<div class="samepart-b">some html b</div>
<div class="samepart-c">some html c</div>

07-28 09:35