CSS Selectors Practical Examples and Usage Patterns

Attribute Selector Example

To target a span element with a specific title attribute value:

const targetElement = document.querySelector("#sale-card .next-cascader-menu li span[title='honor/荣耀']");
if (targetElement) {
  targetElement.click();
}

Pseudo-class Selectors

CSS pseudo-classes for targeting elements based on their position:

/* Select even-positioned list items */
li:nth-child(2n) {
  background-color: #f0f0f0;
}

/* Select odd-positioned list items */
li:nth-child(2n+1) {
  background-color: #e0e0e0;
}

The nth-child() selector counts all child elements regardless of type, while nth-of-type() only considers elements of the specified tag.

Pseudo-element Selectors Implementation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Selector Examples</title>
    <style>
        /* Target first li element specifically */
        li:first-of-type {
            background-color: crimson;
        }

        /* Direct child combinator */
        nav > ul {
            border: 2px solid blue;
        }

        /* Adjacent sibling selector */
        header + main {
            margin-top: 20px;
        }

        /* General sibling selector */
        article ~ aside {
            font-style: italic;
        }

        /* Class combination selectors */
        .highlight.primary {
            color: orange;
            font-weight: bold;
        }

        .text.muted {
            opacity: 0.6;
        }
    </style>
</head>
<body>
    <nav>
        <ul>
            <li>Home</li>
            <li>About</li>
            <li>Contact</li>
        </ul>
    </nav>
    
    <header>Page Header</header>
    <main>Main Content</main>
    <aside>Sidebar Content</aside>
    
    <article>Article Content</article>
    <aside>Another Sidebar</aside>
    
    <div class="highlight primary">Important Text</div>
    <p class="text muted">Secondary Information</p>
</body>
</html>

Key distinctions between similar selectors:

  • nth-child(n) considers all siblings regardless of element type
  • nth-of-type(n) targets the nth occurrence of a specific element type
  • Child combinators (>) only select direct descendants
  • Sibling selectors (+ for adjacent, ~ for general) target elements at the same nesting level

Tags: css selectors pseudo-classes attribute-selectors dom-manipulation

Posted on Thu, 07 May 2026 06:38:25 +0000 by rotto