Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Last active January 31, 2023 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/4d79ff85d2d2ae2605ec5d42575cccd9 to your computer and use it in GitHub Desktop.
Save aspose-com-gists/4d79ff85d2d2ae2605ec5d42575cccd9 to your computer and use it in GitHub Desktop.
How to Use CSS Selector in C# - QuerySelector & QuerySelectorAll in HTML .NET
// Prepare path to source HTML file
string documentPath = "queryselector.html";
// Create an instance of an HTML document
var document = new Aspose.Html.HTMLDocument(documentPath);
// Here we create a CSS Selector that extracts the first paragraph element in the document
var element = document.QuerySelector("p");
// Print content of the first paragraph
Console.WriteLine(element.InnerHTML);
// output: The QuerySelector() method returns the first element in the document that matches the specified selector.
// Set style attribute with properties for the selected element
element.SetAttribute("style", "color:rgb(50,150,200); background-color:#e1f0fe;");
// Save the HTML document to a file
document.Save("queryselector-p.html");
// Prepare output path for HTML document saving
string savePath = "css-selector-color.html";
// Prepare path to source HTML file
string documentPath = "spring.html";
// Create an instance of an HTML document
var document = new Aspose.Html.HTMLDocument(documentPath);
// Here we create a CSS Selector that extracts all elements whose 'class' attribute equals 'square2'
var elements = document.QuerySelectorAll(".square2");
// Iterate over the resulted list of elements
foreach (Aspose.Html.HTMLElement element in elements)
{
// Set style attribute with new background-color property
element.Style.BackgroundColor = "#b0d7fb";
}
// Save the HTML document to a file
document.Save(savePath);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment