You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JS中获取类名含samepart-的HTML元素(无需额外类)

解决方法:获取类名包含指定字符串的元素

Hey there! The issue with document.getElementsByClassName is that it only works with exact class names — it can't handle partial matches like your CSS attribute selector does. But don't worry, we've got a straightforward solution that reuses the same logic as your existing CSS, no extra classes required.


Use document.querySelectorAll() with your existing CSS selector

Since your CSS already uses tag[class*="samepart-"] to target elements with class names containing "samepart-", you can reuse this exact selector directly in JavaScript with querySelectorAll(). This method supports any valid CSS selector, making it perfect for your use case.

Example code:

// Grab ALL elements (any tag) where class contains "samepart-"
const targetElements = document.querySelectorAll('[class*="samepart-"]');

// If you only want <div> elements specifically, add the tag prefix:
const targetDivs = document.querySelectorAll('div[class*="samepart-"]');

How this works:

  • [class*="samepart-"] is the CSS substring matching attribute selector — it matches any element whose class attribute contains the exact substring "samepart-", just like your CSS rule.
  • querySelectorAll() returns a static NodeList of all matching elements, which you can iterate over with forEach() (or convert to an array if you need access to full array methods).

Iterating over the matched elements

Once you have the elements, you can loop through them to perform actions like modifying content, styles, or adding event listeners:

targetElements.forEach(element => {
  // Example: Log each element's content
  console.log(element.textContent);
  // Example: Add a subtle border to each matched div
  element.style.border = '1px solid #eee';
});

内容的提问来源于stack exchange,提问作者TessavWalstijn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:24:33