CSS Selectors in HTML C#

You can apply different rules to CSS rules by using CSS selectors. This article explains the details along with the examples of QuerySelector and QuerySelectorAll methods. You can use these CSS selectors to navigate HTML documents or to create a search pattern to match elements in an HTML document.

Use CSS Selectors in HTML - C# API Installation

Aspose.HTML for .NET API can be used to create, edit, manipulate, or convert HTML documents along with several other file formats. You can easily configure it by downloading the reference DLL file from the Downloads section or running the following NuGet installation command:

PM> Install-Package Aspose.Html

Use CSS Selector QuerySelector in C#

You can style a selected element or navigate the HTML file with the QuerySelector method. The following steps explain how to style a selected element that matches the selector:

  1. Create an instance of HTMLDocument class.
  2. Create a CSS selector to extract the first paragraph element.
  3. Set the style attribute and save the updated HTML file.

The code snippet below shows how to use CSS selectors QuerySelector to process a selected element in the HTML document:

Work with QuerySelectorAll CSS Selector in HTML using C#

Sometimes you may need to process all occurrences of an element. Please follow the steps below to work with QuerySelectorAll CSS selector:

  1. Load the input HTML file with HTMLDocument class.
  2. Create a CSS selector to extract all elements of a class.
  3. Iterate through the elements and set style attributes.
  4. Save the updated HTML document.

The following code sample demonstrates how to use the CSS selector QuerySelectorAll programmatically in C#:

Explore Aspose.HTML for .NET

You may visit the documentation space to explore different chapters that address different features of the API.

Get Free License

You can evaluate the API to its full capacity by requesting a free temporary license.

Conclusion

In this article, you have learned how to use CSS selectors while considering the examples of QuerySelector and QuerySelectorAll selectors. In case of any queries, please feel free to write to us at forum.

See Also

Merge EPUB Files in C#