首页 > 解决方案 > 如何通过css检查列表是否包含第一个元素

问题描述

标签: javascriptcss

解决方案


CSS 并不是真正为这种情况而设计的,但它可以使用 JavaScript。

最好的办法是更加语义化地构建 HTML,并在需要的地方使用类。

但是由于您是动态生成 HTML 并且无法控制输出,因此这里有一个 JS 解决方案。

    document.querySelectorAll('ul li').forEach(element => {
        if (element.innerHTML.startsWith('<strong>') ) {
            element.querySelector('strong').style = 'color:red'
        }
    })
    <div class="container">
        <ul>
            <li class="info">Testing Bold text in custom bullets</li>
            <li class="info"><strong>Testing</strong> Bold text in custom bullets</li>
            <li class="info">Testing <strong>Bold</strong> text in custom bullets</li>
            <li class="info">Testing Bold <strong>text</strong> in custom bullets</li>
            <li class="info">Testing Bold text <strong>in</strong> custom bullets</li>
            <li class="info">Testing Bold text in <strong>custom</strong> bullets</li>
            <li class="info">Testing Bold text in custom <strong>bullets</strong></li>
            <li class="info">Testing Bold text in custom bullets</li>
        </ul>
    </div>


推荐阅读