AngleSharp and Wrapping Element with Element
AngleSharp is a HTML parser library for .NET. Previously I’ve mainly used Html Agility Pack for parsing, but AngleSharp seems to be getting quite much traction nowadays.
I had a scenario where I wanted to use AngleSharp to wrap all the images with links. Given the following HTML:
<img src="2019-02-17-13-10-47.png" class="img-fluid" alt="Test stuff">
I wanted to transform it to this:
<a href="2019-02-17-13-10-47.png" class="lightbox"> <img src="2019-02-17-13-10-47.png" class="img-fluid" alt="Test stuff"> </a>
Here’s how you can do this:
- Create the new link wrapper
- Get image’s original parent element
- Replace the image parent element’s image with the link wrapper
- Set image as the child of the wrapper
In C# using AngleSharp:
var wrapperLink = document.CreateElement("a"); wrapperLink.SetAttribute("href", image.GetAttribute("src")); wrapperLink.ClassName = "lightbox"; var imageParent = image.ParentElement; imageParent.ReplaceChild(wrapperLink, image); wrapperLink.AppendChild(image);Where document is of type IHtmlDocument and image is of type IHtmlImageElement.