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

如何在单一JavaScript文件中为动态创建的div元素设置伪元素样式

How to Style Pseudo-elements for Dynamically Created Divs in a Single JavaScript File

Got it, I get your challenge—you need to keep all HTML/CSS/JS in one JS file, and you're stuck on applying those scrollbar pseudo-element styles to your dynamically created div. The issue here is that pseudo-elements like ::-webkit-scrollbar can't be set directly via an element's style property (that only works for inline styles on the element itself). Instead, we need to inject a CSS rule into the document's stylesheet or add a <style> tag dynamically.

Here's a straightforward way to do this all within your JavaScript file:

  • Create a dynamic style element and add your pseudo-element CSS rules to it.
  • Append this style element to the document's <head> so the styles are applied globally.
  • Create your div as before—since it has the cart-container class, the pseudo-element styles will target it automatically.

Working Code Example:

// Step 1: Create and populate a style tag with scrollbar pseudo-element styles
const scrollbarStyle = document.createElement('style');
scrollbarStyle.textContent = `
  .cart-container::-webkit-scrollbar {
    width: 10px;
  }
  .cart-container::-webkit-scrollbar-thumb {
    border-radius: 5px;
    background-color: #30808d;
    height: 100px;
  }
`;

// Step 2: Add the style tag to the document head
document.head.appendChild(scrollbarStyle);

// Step 3: Create your dynamic div (your original code, plus appending to DOM)
let myDiv = document.createElement('div');
myDiv.className = 'cart-container';
myDiv.style.cssText = "height: 440px; width: 400px; margin: auto; overflow-y:auto;";
document.body.appendChild(myDiv); // Don't forget to add the div to the DOM!

Quick Notes:

  • This approach keeps all your code self-contained in the JS file, which fits your challenge requirements.
  • The ::-webkit-scrollbar pseudo-elements are specific to WebKit browsers (Chrome, Safari, Edge). If you need cross-browser support for scrollbars, you'd have to add additional vendor prefixes or use newer standard scrollbar properties, but this works perfectly for the rules you provided.
  • By adding the style to the <head>, any element with the cart-container class (even dynamically created ones) will get the scrollbar styles applied.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 21:17:31