You can read more details at: Use CSS Selectors in HTML using C#
Last active
January 31, 2023 16:00
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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