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
1using Aspose.Html;
2using System.IO;
3...
4
5 // Prepare path to source HTML file
6 string documentPath = Path.Combine(DataDir, "queryselector.html");
7
8 // Create an instance of an HTML document
9 var document = new HTMLDocument(documentPath);
10
11 // Here we create a CSS Selector that extracts the first paragraph element in the document
12 var element = document.QuerySelector("p");
13
14 // Print content of the first paragraph
15 Console.WriteLine(element.InnerHTML);
16 // output: The QuerySelector() method returns the first element in the document that matches the specified selector.
17
18 // Set style attribute with properties for the selected element
19 element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe;");
20
21 // Save the HTML document to a file
22 document.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
1using Aspose.Html;
2using System.IO;
3...
4
5 // Prepare output path for HTML document saving
6 string savePath = Path.Combine(OutputDir, "css-celector-style.html");
7
8 // Prepare path to source HTML file
9 string documentPath = Path.Combine(DataDir, "nature.html");
10
11 // Create an instance of an HTML document
12 var document = new HTMLDocument(documentPath);
13
14 // Create a CSS Selector that selects <div> element that is the last child of its parent
15 var element = document.QuerySelector("div:last-child");
16
17 // Set style attribute with properties for the selected element
18 element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe; text-align:center");
19
20 // Save the HTML document to a file
21 document.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
1using Aspose.Html;
2using System.IO;
3...
4
5 // Prepare output path for HTML document saving
6 string savePath = Path.Combine(OutputDir, "css-selector-color.html");
7
8 // Prepare path to source HTML file
9 string documentPath = Path.Combine(DataDir, "spring.html");
10
11 // Create an instance of an HTML document
12 var document = new HTMLDocument(documentPath);
13
14 // Here we create a CSS Selector that extracts all elements whose 'class' attribute equals 'square2'
15 var elements = document.QuerySelectorAll(".square2");
16
17 // Iterate over the resulted list of elements
18 foreach (HTMLElement element in elements)
19 {
20 // Set style attribute with new background-color property
21 element.Style.BackgroundColor = "#b0d7fb";
22 }
23
24 // Save the HTML document to a file
25 document.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.