protected CQ InsertAtOffset(CQ target, int offset, out CQ insertedElements)
{
// Copy the target list: it could change otherwise
List<IDomObject> targets = new List<IDomObject>(target);
bool isTargetDisconnected = (target.CsQueryParent != null && target.Document != target.CsQueryParent.Document) ||
targets.Any(item => item.ParentNode == null);
bool isFirst = true;
insertedElements = NewCqUnbound();
// bind the source to the target's document if it was itself a CsQuery object, and update its selection set to reflect the
// current document.
Document = target.Document;
if (isTargetDisconnected)
{
// When the target is disconnected, just append elements to the selection set, not to the DOM
CQ result = NewCqInDomain();
result.CsQueryParent = this.CsQueryParent;
if (offset == 0)
{
result.AddSelection(Selection);
}
result.AddSelection(target);
if (offset == 1)
{
result.AddSelection(Selection);
}
result.SelectionSet.OutputOrder = SelectionSetOrder.OrderAdded;
insertedElements.AddSelection(Selection);
return result;
}
else
{
foreach (var el in targets)
{
bool isElDisconnected = el.ParentNode == null;
if (isFirst)
{
insertedElements.AddSelection(SelectionSet);
InsertAtOffset(el, offset);
isFirst = false;
}
else
{
var clone = this.Clone();
clone.InsertAtOffset(el, offset);
insertedElements.AddSelection(clone);
}
}
}
return target;
}
#endregion