我想获取一系列数字之间的元素,比如说 10 到 15 之间:
<div class="1">....</div>
<div class="2">....</div>
<div class="3">....</div>
...
...
...
<div class="20">....</div>
所需输出:
<div class="10">....</div>
<div class="11">....</div>
<div class="12">....</div>
<div class="13">....</div>
<div class="14">....</div>
<div class="15">....</div>
最佳答案
虽然 JS 解决方案可能更好,主要是因为它更灵活,但我想提一下 CSS 解决方案,尽管它有更多限制。
#parent {
display: inline-block;
}
div {
border: 1px solid #333;
padding: 5px;
}
div div {
width: 50px;
}
div:nth-child(n+10):nth-child(-n+15) { /* From the 10th child up to the 15th child */
background-color: green;
}
<div id="parent">
<div>01</div>
<div>02</div>
<div>03</div>
<div>04</div>
<div>05</div>
<div>06</div>
<div>07</div>
<div>08</div>
<div>09</div>
<div>10</div>
<div>11</div>
<div>12</div>
<div>13</div>
<div>14</div>
<div>15</div>
<div>16</div>
<div>17</div>
<div>18</div>
<div>19</div>
<div>20</div>
</div>
通过组合两个nth-child
选择器,您可以指定一系列元素。
您也可以在 JS 中使用此选择器
document.querySelectorAll('div:nth-child(n+10):nth-child(-n+15)');
缺点是,只有当所有元素都是同级元素并且是父元素的唯一子元素时,它才能正常工作。
关于javascript - 如何获取一系列数字之间的 div 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70270785/