How to use CSS Selector – QuerySelector, QuerySelectorAll
CSS selectors are used to select the HTML elements you want to style and apply a set of CSS rules. Moreover, you can navigate an HTML document using CSS Selectors and extract information about selected elements or edit them. CSS Selectors are used to declare which of the markup elements a style applies to, a kind of match expression. Aspose.HTML API allows you to create a search pattern to match elements in a document tree based on CSS Selectors syntax.
In this article, discover how to effectively apply selectors to select the elements you want to style using
QuerySelector(selector
) and
QuerySelectorAll(selector
) methods of the
Document class. Methods allow you to quickly and easily retrieve element nodes from the DOM by matching against selectors. You can select elements by class, id or name, or any complex CSS selector.
For more information on how to effectively apply selectors to select the elements you want to style, please visit the article CSS Selectors. You will cover Basic Selectors, Combinator Selectors, Attribute Selectors, Group Selectors and Pseudo Selectors.
You can download the complete examples and data files from GitHub.
QuerySelector() to Navigate HTML
The QuerySelector() method is used to query a DOM element that matchs a CSS selector. It returns the first element in the document that matches the specified selector. If no matches are found, null is returned. In the following example, we use CSS Element Selector to find the first paragraph element and output its contents to the Console:
C# Example
1// Prepare path to source HTML file
2string documentPath = Path.Combine(DataDir, "queryselector.html");
3
4// Create an instance of an HTML document
5var document = new HTMLDocument(documentPath);
6
7// Here we create a CSS Selector that extracts the first paragraph element
8var element = document.QuerySelector("p");
9
10// Print content of the first paragraph
11Console.WriteLine(element.InnerHTML);
12// output: The QuerySelector() method returns the first element in the document that matches the specified selector.
13
14// Set style attribute with properties for the selected element
15element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe;");
16
17// Save the HTML document to a file
18document.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 selector to determine what an element should be returned and returns the first matching element in the node’s subtree. If no matching node is found, null is returned. In the following C# example, QuerySelector() method takes as a parameter div:last-child
selector that means to select <div>
element that is the last child of its parent. Note: The QuerySelector() method returns the first element that matches the selector.
C# Example
1// Prepare output path for HTML document saving
2string savePath = Path.Combine(OutputDir, "css-celector-style.html");
3
4// Prepare path to source HTML file
5string documentPath = Path.Combine(DataDir, "nature.html");
6
7// Create an instance of an HTML document
8var document = new HTMLDocument(documentPath);
9
10// Create a CSS Selector that selects <div> element that is the last child of its parent
11var element = document.QuerySelector("div:last-child");
12
13// Set the style attribute with properties for the selected element
14element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe; text-align:center");
15
16// Save the HTML document to a file
17document.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.
QuerySelectorAll() to Style Selected Elements
If you want a list of all elements that match the specified selectors, you should 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:
C# Example
1// Prepare output path for HTML document saving
2string savePath = Path.Combine(OutputDir, "css-selector-color.html");
3
4// Prepare path to source HTML file
5string documentPath = Path.Combine(DataDir, "spring.html");
6
7// Create an instance of an HTML document
8var document = new HTMLDocument(documentPath);
9
10// Here we create a CSS Selector that extracts all elements whose 'class' attribute equals 'square2'
11var elements = document.QuerySelectorAll(".square2");
12
13// Iterate over the resulted list of elements
14foreach (HTMLElement element in elements)
15{
16 // Set the style attribute with new background-color property
17 element.Style.BackgroundColor = "#b0d7fb";
18}
19
20// Save the HTML document to a file
21document.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):
Aspose.HTML offers free HTML Web Applications that are an online collection of converters, mergers, SEO tools, HTML code generators, URL tools, and more. The applications work on any operating system with a web browser and do not require any additional software installation. It’s a fast and easy way to efficiently and effectively solve your HTML-related tasks.