如何在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 whoseclassattribute contains the exact substring "samepart-", just like your CSS rule.querySelectorAll()returns a staticNodeListof all matching elements, which you can iterate over withforEach()(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

