Use CSS Selectors in C# – QuerySelector and QuerySelectorAll

To use CSS selectors in C#, load an HTMLDocument, call QuerySelector() for the first matching element or QuerySelectorAll() for all matches, then read content or update styles in the DOM.

CSS selectors are used to select HTML elements for styling, extraction, or DOM editing. In Aspose.HTML for .NET, the QuerySelector(selector) and QuerySelectorAll(selector) methods of the Document class let you retrieve elements by tag name, class, id, attributes, pseudo selectors, and more complex CSS selector expressions.

This article shows how to use selectors to extract text, style one matched element, and style all elements that match a class selector. For selector syntax details, see CSS Selectors.

QuerySelector() to Navigate HTML

The QuerySelector() method queries a DOM element that matches a CSS selector. It returns the first matching element in the document. If no match is found, it returns null. In the following example, a CSS element selector finds the first paragraph and outputs its contents to the console:

Extract Paragraph Content with QuerySelector in C#

 1// Extract HTML content using CSS selector
 2
 3// Prepare path to source HTML file
 4string documentPath = Path.Combine(DataDir, "queryselector.html");
 5
 6// Create an instance of an HTML document
 7HTMLDocument document = new HTMLDocument(documentPath);
 8
 9// Here we create a CSS Selector that extracts the first paragraph element
10Element element = document.QuerySelector("p");
11
12// Print content of the first paragraph  
13Console.WriteLine(element.InnerHTML);
14// output: The QuerySelector() method returns the first element in the document that matches the specified selector.
15
16// Set style attribute with properties for the selected element
17element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe;");
18
19// Save the HTML document to a file
20document.Save(Path.Combine(OutputDir, "queryselector-p.html"));

Moreover, in the C# example, the text color and background color were changed for the selected element. The next HTML code example includes JavaScript that uses querySelector(“p”) method:

JavaScript querySelector()

 1<html>
 2<head>
 3</head>
 4	<body>
 5		<h1>QuerySelector() Method</h1>
 6		<p>The QuerySelector() method returns the first element in the document that matches the specified selector.</p>
 7		<p>CSS Selectors are used to declare which of the markup elements a style applies to, a kind of match expression.</p>
 8	</body>
 9	<script>
10		// Create a CSS Selector that selects the first paragraph element
11        var element = document.querySelector("p");
12
13        // Set style attribute with properties for the selected element
14        element.setAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe");
15	</script>
16</html>

QuerySelector() to Style Selected Element

The QuerySelector() method accepts a selector and returns the first matching element in the node’s subtree. In the following C# example, QuerySelector() uses the div:last-child selector to find a <div> element that is the last child of its parent. Note: QuerySelector() returns only the first element that matches the selector.

Style One Element with QuerySelector in C#

 1// Select and style HTML element with C# CSS selector
 2
 3// Prepare output path for HTML document saving
 4string savePath = Path.Combine(OutputDir, "css-celector-style.html");
 5
 6// Prepare path to source HTML file
 7string documentPath = Path.Combine(DataDir, "nature.html");
 8
 9// Create an instance of an HTML document
10HTMLDocument document = new HTMLDocument(documentPath);
11
12// Create a CSS Selector that selects <div> element that is the last child of its parent
13Element element = document.QuerySelector("div:last-child");
14
15// Set the style attribute with properties for the selected element
16element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe; text-align:center");
17
18// Save the HTML document to a file
19document.Save(Path.Combine(savePath));

JavaScript querySelector()

1<script>
2	// Create a CSS Selector that selects <div> element that is the 2-d child of its parent
3	var element = document.querySelector("div:nth-child(2)");
4
5	// Set style attribute with properties for the selected element
6	element.setAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe; text-align:center");
7</script>

Let’s look at the result of using the QuerySelector() method to restyle the <div> element that matches the selector: a) an image of original HTML document; b) the image of the HTML document after changing the style.

HTML document before and after styling a selected div with QuerySelector in C#

QuerySelectorAll() to Style Selected Elements

If you want a list of all elements that match a selector, use the QuerySelectorAll() method.

In the following example, we use the QuerySelectorAll() method for navigation through an HTML document and searching for the needed elements. This method takes as a parameter the query selector and returns a NodeList of all the elements, which match the specified selector. We select all elements whose class attribute equals square2 and recolor them:

Style Multiple Elements with QuerySelectorAll in C#

 1// Apply background color to elements by class using C#
 2
 3// Prepare output path for HTML document saving
 4string savePath = Path.Combine(OutputDir, "css-selector-color.html");
 5
 6// Prepare path to source HTML file
 7string documentPath = Path.Combine(DataDir, "spring.html");
 8
 9// Create an instance of an HTML document
10HTMLDocument document = new HTMLDocument(documentPath);
11
12// Here we create a CSS Selector that extracts all elements whose 'class' attribute equals 'square2'
13NodeList elements = document.QuerySelectorAll(".square2");
14
15// Iterate over the resulted list of elements
16foreach (HTMLElement element in elements)
17{
18    // Set the style attribute with new background-color property
19    element.Style.BackgroundColor = "#b0d7fb";
20}
21
22// Save the HTML document to a file
23document.Save(Path.Combine(savePath));

JavaScript querySelectorAll()

1<script>
2	// Create a CSS Selector that extracts all elements whose 'class' attribute equals 'square2'
3	var elements = document.querySelectorAll(".square2");
4
5	// Iterate over the resulted list of elements and set style background-color property
6	for(var i = 0; i < elements.length; i++){
7	document.querySelectorAll(".square2")[i].style.backgroundColor = "#b0d7fb";
8	}
9</script>

All elements with class="square2" were recolored. The figure shows the result of applying the QuerySelectorAll() method (b) to the source file spring.html (a):

HTML elements with class square2 before and after styling with QuerySelectorAll in C#

FAQ

When should I use QuerySelector instead of QuerySelectorAll?

Use QuerySelector() when you need only the first matching element. Use QuerySelectorAll() when every matching element should be inspected or updated.

Can I use class, id, and pseudo selectors?

Yes. The selector string can use standard CSS selector syntax, including class selectors, id selectors, attribute selectors, and pseudo selectors supported by the DOM query.

What happens if no element matches the selector?

QuerySelector() returns null. Check the result before reading content or setting style properties.

Related Articles