ParentNodeExtensions
Useful methods for parent node objects.
using AngleSharp.Dom;
using System;
using System.Collections.Generic;
using System.Linq;
namespace AngleSharp.Extensions
{
internal static class ParentNodeExtensions
{
public static INode MutationMacro(this INode parent, INode[] nodes)
{
if (nodes.Length > 1) {
IDocumentFragment documentFragment = parent.Owner.CreateDocumentFragment();
for (int i = 0; i < nodes.Length; i++) {
documentFragment.AppendChild(nodes[i]);
}
return documentFragment;
}
return nodes[0];
}
public static void PrependNodes(this INode parent, params INode[] nodes)
{
if (nodes.Length != 0) {
INode node = parent.MutationMacro(nodes);
parent.PreInsert(node, parent.FirstChild);
}
}
public static void AppendNodes(this INode parent, params INode[] nodes)
{
if (nodes.Length != 0) {
INode node = parent.MutationMacro(nodes);
parent.PreInsert(node, null);
}
}
public static void InsertBefore(this INode child, params INode[] nodes)
{
INode parent = child.Parent;
if (parent != null && nodes.Length != 0) {
INode node = parent.MutationMacro(nodes);
parent.PreInsert(node, child);
}
}
public static void InsertAfter(this INode child, params INode[] nodes)
{
INode parent = child.Parent;
if (parent != null && nodes.Length != 0) {
INode node = parent.MutationMacro(nodes);
parent.PreInsert(node, child.NextSibling);
}
}
public static void ReplaceWith(this INode child, params INode[] nodes)
{
INode parent = child.Parent;
if (parent != null) {
if (nodes.Length != 0) {
INode newChild = parent.MutationMacro(nodes);
parent.ReplaceChild(newChild, child);
} else
parent.RemoveChild(child);
}
}
public static void RemoveFromParent(this INode child)
{
child.Parent?.PreRemove(child);
}
public static IEnumerable<TNode> DescendentsAndSelf<TNode>(this INode parent)
{
return parent.DescendentsAndSelf().OfType<TNode>();
}
public static IEnumerable<INode> DescendentsAndSelf(this INode parent)
{
if (parent == null)
throw new ArgumentNullException("parent");
return parent.GetDescendantsAndSelf();
}
}
}