代码之家  ›  专栏  ›  技术社区  ›  Chris Abbott

如何选择匿名嵌套子元素?

  •  0
  • Chris Abbott  · 技术社区  · 8 年前

    如果没有一个子元素具有唯一的id,我如何在CSS中单独选择该分组中的每个子元素?

    <g class="element-group">
       <g class="element">
          <rect class="element-shape bundle-shape" 
             x="101.778125" 
             width="131"
             y="36.44939999999999" 
             height="138.5466" 
             style="fill: rgb(230, 204, 102); 
             stroke-width: 0px; 
             stroke: rgb(0, 128, 128);">
          </rect>
       </g>
    
       <g class="element">
          ...
       </g>
    
       <g class="element">
          ...
       </g>
    </g>
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   D-Money    8 年前

    不确定您到底想做什么,但如果是特定于CSS的,您可以使用 nth-child 选择器:

    .element:nth-child(2) {...} // replace 2 with whatever index you want.
    

    如果你在谈论JS,那么你可以使用:

    var elements = document.getElementsByClassName('element');
    console.log(elements[2]); // replace 2 with whatever index you want.