Working With Selectors

Guide to Using CSS Selectors and XPaths on the DOM

CSS Selectors

CSS selectors allow you to select and style HTML elements efficiently. They are widely used in styling and JavaScript DOM manipulation.

Basic CSS Selectors

SelectorDescriptionExampleMatches
*Selects all elements*<div>, <p>, <h1>
tagnameSelects elements by tagp<p>Paragraph</p>
#idSelects an element by ID#main<div id="main">
.classSelects elements by class.btn<button class="btn">Click</button>
element1, element2Selects multiple elementsh1, p<h1>Title</h1><p>Text</p>

Combinators

SelectorDescriptionExampleMatches
ancestor descendantSelects nested elementsdiv pAll <p> inside <div>
parent > childSelects direct childrendiv > pOnly direct <p> children of <div>
element + siblingSelects next siblingh1 + pThe first <p> after <h1>
element ~ siblingsSelects all following siblingsh1 ~ pAll <p> after <h1>

Attribute Selectors

SelectorDescriptionExampleMatches
[attr]Elements with attribute[disabled]<button disabled>
[attr="value"]Exact match[type="text"]<input type="text">
[attr^="value"]Starts with[href^="https"]<a href="https://">
[attr$="value"]Ends with[src$=".jpg"]<img src="image.jpg">
[attr*="value"]Contains[class*="btn"]<button class="btn-primary">

Pseudo-classes

SelectorDescriptionExampleMatches
:first-childFirst child of parentp:first-childFirst <p> inside a parent
:last-childLast child of parentp:last-childLast <p> inside a parent
:nth-child(n)Specific childli:nth-child(2)The second <li> in a list
:hoverWhen hoveredbutton:hoverWhen hovering over <button>
:focusWhen focusedinput:focusA focused <input>

XPath

XPath is a powerful query language for selecting elements in XML and HTML. It is commonly used in web scraping and automation.

Basic Syntax

ExpressionDescriptionExampleMatches
/Root node/htmlThe <html> element
//Any descendant//pAll <p> elements
.Current node./span<span> inside current node
..Parent node../divParent <div>

Node Selection

SelectorDescriptionExampleMatches
//tagnameSelects all matching tags//h2All <h2> elements
//tagname[@attr="value"]Attribute match//a[@class="nav"]<a class="nav">
//tagname[text()="text"]Exact text match//button[text()="Submit"]<button>Submit</button>

Functions and Operators

FunctionDescriptionExampleMatches
contains()Partial match//p[contains(text(), "Hello")]Any <p> with “Hello” in text
starts-with()Starts with match//input[starts-with(@name, "user")]<input name="username">
position()Selects nth element//li[position()=1]First <li>
last()Last element//tr[last()]Last <tr> in a table

Combinations

SelectorDescriptionExampleMatches
//div//pAll <p> inside <div>//div//pNested <p> elements
//div/pDirect <p> children of <div>//div/pImmediate children
//*[@id="header"]//aAll <a> under element with id="header"//*[@id="header"]//aAny nested <a>