toString methods used to optionally take a Phobos appender,
but now it takes a private internal implementation as of August 26, 2025. This may change again.
This is an html DOM implementation, started with cloning what the browser offers in Javascript, but going well beyond it in convenience.
If you can do it in Javascript, you can probably do it with this module, and much more.
import arsd.dom;
void main() {
auto document = new Document("<html><p>paragraph</p></html>");
writeln(document.querySelector("p"));
document.root.innerHTML = "<p>hey</p>";
writeln(document);
}BTW: this file optionally depends on arsd.characterencodings, to help it correctly read files from the internet. You should be able to get characterencodings.d from the same place you got this file.
If you want it to stand alone, just always use the Document.parseUtf8 function or the constructor that takes a string.
Symbol_groups:
core_functionality =
These members provide core functionality. The members on these classes will provide most your direct interaction.
bonus_functionality =
These provide additional functionality for special use cases.
implementations =
These provide implementations of other functionality.
toString methods used to optionally take a Phobos appender,
but now it takes a private internal implementation as of August 26, 2025. This may change again.
The main document interface, including a html or xml parser.
There's three main ways to create a Document:
If you want to parse something and inspect the tags, you can use the [this|constructor]:
// create and parse some HTML in one call
auto document = new Document("<html></html>");
// or some XML
auto document = new Document("<xml></xml>", true, true); // strict mode enabled
// or better yet:
auto document = new XmlDocument("<xml></xml>"); // specialized subclassIf you want to download something and parse it in one call, the [fromUrl] static function can help:
auto document = Document.fromUrl("http://dlang.org/");(note that this requires my arsd.characterencodings and arsd.http2 libraries)
And, if you need to inspect things like <%= foo %> tags and comments, you can add them to the dom like this, with the [enableAddingSpecialTagsToDom] and [parseUtf8] or [parseGarbage] functions:
auto document = new Document();
document.enableAddingSpecialTagsToDom();
document.parseUtf8("<example></example>", true, true); // changes the trues to false to switch from xml to html modeYou can also modify things like [selfClosedElements] and [rawSourceElements] before calling the parse family of functions to do further advanced tasks.
However you parse it, it will put a few things into special variables.
[root] contains the root document. [prolog] contains the instructions before the root (like <!DOCTYPE html>). To keep the original things, you will need to [enableAddingSpecialTagsToDom] first, otherwise the library will return generic strings in there. [piecesBeforeRoot] will have other parsed instructions, if [enableAddingSpecialTagsToDom] is called. [piecesAfterRoot] will contain any xml-looking data after the root tag is closed.
Most often though, you will not need to look at any of that data, since Document itself has methods like [querySelector], [appendChild], and more which will forward to the root [Element] for you. Group: core_functionality
string _contentTypebool delegate(string) parseSawCommentIf the parser sees a html comment, it will call this callback <!-- comment --> will call parseSawComment(" comment ") Return true if you want the node appended to the document. It will be in a [Htm...bool delegate(string) parseSawAspCodeIf the parser sees <% asp code... %>, it will call this callback. It will be passed "% asp code... %" or "%= asp code .. %" Return true if you want the node appended to the document. It will be in ...bool delegate(string) parseSawPhpCodeIf the parser sees <?php php code... ?>, it will call this callback. It will be passed "?php php code... ?" or "?= asp code .. ?" Note: dom.d cannot identify the other php <? code ?> short format....bool delegate(string) parseSawQuestionInstructionif it sees a <?xxx> that is not php or asp it calls this function with the contents. <?SOMETHING foo> calls parseSawQuestionInstruction("?SOMETHING foo") Unlike the php/asp ones, this ends on the f...bool delegate(string) parseSawBangInstructionif it sees a <! that is not CDATA or comment (CDATA is handled automatically and comments call parseSawComment), it calls this function with the contents. <!SOMETHING foo> calls parseSawBangInstruc...immutable(string)[] selfClosedElementsList of elements that can be assumed to be self-closed in this document. The default for a Document are a hard-coded list of ones appropriate for HTML. For [XmlDocument], it defaults to empty. You ...immutable(string)[] rawSourceElementsList of elements that contain raw CDATA content for this document, e.g. `<script>` and `<style>` for HTML. The parser will read until the closing string and put everything else in a [RawSource] obj...immutable(string)[] inlineElementsList of elements that are considered inline for pretty printing. The default for a Document are hard-coded to something appropriate for HTML. For [XmlDocument], it defaults to empty. You can modify...private string _prologprivate bool prologWasSetElement rootThe root element, like `<html>`. Most the methods on Document forward to this object.Element[] piecesBeforeRootif these were kept, this is stuff that appeared before the root element, such as <?xml version ?> decls and <!DOCTYPE>sElement[] piecesAfterRootstuff after the root, only stored in non-strict mode and not used in toString, but available in case you want itbool loose.void delegate(DomMutationEvent)[] eventObserversinout(Document) asDocument() inoutvoid processTagOpen(Element what)These three functions, `processTagOpen`, `processTagClose`, and `processNodeWhileParsing`, allow you to process elements as they are parsed and choose to not append them to the dom tree.void processTagClose(Element what)dittovoid processNodeWhileParsing(Element parent, Element child)dittoDocument fromUrl()(string url, bool strictMode = false) staticConvenience method for web scraping. Requires [arsd.http2] to be included in the build as well as [arsd.characterencodings].ElementCollection opIndex(string selector)This is just something I'm toying with. Right now, you use opIndex to put in css selectors. It returns a struct that forwards calls to all elements it holds, and returns itself so you can chain it.string contentType(string mimeType) @propertyIf you're using this for some other kind of XML, you can set the content type here.string filename() @property constimplementing the FileResource interface, useful for sending via http automatically.string contentType() @property constimplementing the FileResource interface, useful for sending via http automatically.void enableAddingSpecialTagsToDom()This will set delegates for parseSaw* (note: this overwrites anything else you set, and you setting subsequently will overwrite this) that add those things to the dom tree when it sees them. Call t...void parseGarbage()(string data)Given the kind of garbage you find on the Internet, try to make sense of it. Equivalent to document.parse(data, false, false, null); (Case-insensitive, non-strict, determine character encoding from...void parseStrict(string data, bool pureXmlMode = false)Parses well-formed UTF-8, case-sensitive, XML or XHTML Will throw exceptions on things like unclosed tags.void parseUtf8(string data, bool caseSensitive = false, bool strict = false)Parses well-formed UTF-8 in loose mode (by default). Tries to correct tag soup, but does NOT try to correct bad character encodings.Utf8Stream handleDataEncoding()(in string rawdata, string dataEncoding, bool strict)Utf8Stream toUtf8Stream(in string rawdata)void parse()(in string rawdata, bool caseSensitive = false, bool strict = false, string dataEncoding = "UTF-8")Take XMLish data and try to make the DOM tree out of it.void parseStream(Utf8Stream data, bool caseSensitive = false, bool strict = false, bool pureXmlMode = false)Element getElementById(string id)These functions all forward to the root element. See the documentation in the Element class.SomeElementType requireElementById(SomeElementType = Element)(string id, string file = __FILE__, size_t line = __LINE__) if( is(SomeElementType : Element))dittoSomeElementType requireSelector(SomeElementType = Element)(string selector, string file = __FILE__, size_t line = __LINE__) if( is(SomeElementType : Element))dittoMaybeNullElement!SomeElementType optionSelector(SomeElementType = Element)(string selector, string file = __FILE__, size_t line = __LINE__) if(is(SomeElementType : Element))dittoElement[] getElementsBySelector(string selector)dittoElement getFirstElementByTagName(string tag)FIXME: btw, this could just be a lazy range......Element mainBody()This returns the <body> element, if there is one. (It different than Javascript, where it is called 'body', because body used to be a keyword in D.)string getMeta(string name)this uses a weird thing... it's [name=] if no colon and [property=] if colonvoid setMeta(string name, string value)Sets a meta tag in the document header. It is kinda hacky to work easily for both Facebook open graph and traditional html meta tags/Form createForm().Element createElement(string name).Element createTextNode(string content).void clear().string prolog() @property constReturns or sets the string before the root element. This is, for example, `<!DOCTYPE html>\n` or similar.void setProlog(string d)dittostring toString() constReturns the document as string form. Please note that if there is anything in [piecesAfterRoot], they are discarded. If you want to add them to the file, loop over that and append it yourself (but ...string toPrettyString(bool insertComments = false, int indentationLevel = 0, string indentWith = "\t") constWrites it out with whitespace for easier eyeball debuggingthis(string data, bool caseSensitive = false, bool strict = false)Creates a document with the given source data. If you want HTML behavior, use `caseSensitive` and `struct` set to `false`. For XML mode, set them to `true`.this()Creates an empty document. It has nothing in it at all, ready.This represents almost everything in the DOM and offers a lot of inspection and manipulation functions. Element, or its subclasses, are what makes the dom tree. Group: core_functionality
Element[] childrenstring tagNameThe name of the tag. Remember, changing this doesn't change the dynamic type of the object.AttributesHolder attributesThis is where the attributes are actually stored. You should use getAttribute, setAttribute, and hasAttribute instead.private bool selfClosedIn XML, it is valid to write <tag /> for all elements with no children, but that breaks HTML, so I don't do it here. Instead, this flag tells if it should be. It is based on the source document's n...private DomParent parent_private CssStyle _computedStyleinout(Document) asDocument() inoutElementCollection opIndex(string selector)Returns a collection of elements by selector. See: [Document.opIndex]SomeElementType requireElementById(SomeElementType = Element)(string id, string file = __FILE__, size_t line = __LINE__) if(
is(SomeElementType : Element)
)Calls getElementById, but throws instead of returning null if the element is not found. You can also ask for a specific subclass of Element to dynamically cast to, which also throws if it cannot be...SomeElementType requireSelector(SomeElementType = Element)(string selector, string file = __FILE__, size_t line = __LINE__) if(
is(SomeElementType : Element)
)ditto but with selectors instead of idsMaybeNullElement!SomeElementType optionSelector(SomeElementType = Element)(string selector, string file = __FILE__, size_t line = __LINE__) if(is(SomeElementType : Element))If a matching selector is found, it returns that Element. Otherwise, the returned object returns null for all methods.inout(ClassListHelper) classList() @property inoutReturns a helper object to work with classes, just like javascript.Element addClass(string c) @scriptableAdds a string to the class attribute. The class attribute is used a lot in CSS.Element addChild(string tagName, string childInfo = null, string childInfo2 = null)Family of convenience functions to quickly add a tag with some text or other relevant info (for example, it's a src for an <img> element instead of inner text). They forward to [Element.make] then ...Element addSibling(string tagName, string childInfo = null, string childInfo2 = null)Another convenience function. Adds a child directly after the current one, returning the new child.Element addSibling(Element e)dittovoid addChildren(T...)(T t)Convenience function to append text intermixed with other children. For example: div.addChildren("You can visit my website by ", new Link("mysite.com", "clicking here"), "."); or div.addChildren("H...void appendChildren(Element[] children)Appends the list of children to this element.void reparent(Element newParent)Removes this element form its current parent and appends it to the given `newParent`.void stripOut()Strips this tag out of the document, putting its inner html as children of the parent.Element removeFromTree()shorthand for `this.parentNode.removeChild(this)` with `parentNode` `null` check if the element already isn't in a tree, it does nothing.Element wrapIn(Element what)Wraps this element inside the given element. It's like `this.replaceWith(what); what.appendchild(this);`Element replaceWith(Element e)Replaces this element with something else in the tree.void setValue(string field, string value)void setValue(string field, string[] value)void sendObserverEvent(DomMutationOperations operation, string s1 = null, string s2 = null, Element r = null, Element r2 = null)inout(Document) parentDocument() @property inoutGet the parent Document object that contains this element. It may be null, so remember to check for that.void parentDocument(Document doc) @propertyElement make(string tagName, string childInfo = null, string childInfo2 = null, const string[] selfClosedElements = htmlSelfClosedElements) staticConvenience function to try to do the right thing for HTML. This is the main way I create elements.Element make(Args...)(arsd.core.InterpolationHeader head, Args args, arsd.core.InterpolationFooter foot) staticMakes an element from an interpolated sequence.Element firstChild() @propertyReturns the first child of this element. If it has no children, returns null. Remember, text nodes are children too.Element lastChild() @propertyReturns the last child of the element, or null if it has no children. Remember, text nodes are children too.Element nextInSource()the next or previous element you would encounter if you were reading it in the source. May be a text node or other special non-tag object if you enabled them.Element previousInSource()dittoElement previousElementSibling() @propertyReturns the next or previous sibling that is not a text node. Please note: the behavior with comments is subject to change. Currently, it will return a comment or other nodes if it is in the tree (...Element previousSibling(string tagName = null) @propertyReturns the next or previous sibling matching the `tagName` filter. The default filter of `null` will return the first sibling it sees, even if it is a comment or text node, or anything else. A fil...T getParent(T = Element)(string tagName = null) if(is(T : Element))Gets the nearest node, going up the chain, with the given tagName May return null or throw. The type `T` will specify a subclass like [Form], [Table], or [Link], which it will cast for you when found.Element getElementById(string id)Searches this element and the tree of elements under it for one matching the given `id` attribute.Element querySelector(string selector) @scriptableReturns a child element that matches the given `selector`.bool matches(string selector) @scriptableIf the element matches the given selector. Previously known as `matchesSelector`.Element closest(string selector) @scriptableReturns itself or the closest parent that matches the given selector, or null if none found See_also: https://developer.mozilla.org/en-US/docs/Web/API/Element/closestElement[] querySelectorAll(string selector) @scriptableReturns elements that match the given CSS selectorElement[] getElementsByClassName(string cn)Returns child elements that have the given class name or tag name.Element[] getElementsByTagName(string tag)dittostring getAttribute(string name) @scriptable constGets the given attribute value, or null if the attribute is not set.Element setAttribute(string name, string value) @scriptableSets an attribute. Returns this for easy chainingstring className() @property constGets or sets the class attribute's contents. Returns an empty string if it has no class.string opDispatch(string name)(string v = null) if(isConvenientAttribute(name)) @propertyProvides easy access to common HTML attributes, object style.string opDispatch(string name)(string v = null) if(!isConvenientAttribute(name)) @propertyOld access to attributes. Use [attrs] instead.DataSet dataset() @propertyHTML5's dataset property. It is an alternate view into attributes with the data- prefix. Given `<a data-my-property="cool" />`, we get `assert(a.dataset.myProperty == "cool");`ElementStyle style() @propertyProvides both string and object style (like in Javascript) access to the style attribute.void parseAttributes(string[] whichOnes = null)CssStyle computedStyle() @propertyDon't use this. It can try to parse out the style element but it isn't complete and if I get back to it, it won't be for a while.void removeAllChildren()Removes all inner content from the tag; all child text and elements are gone.Element appendSibling(Element e)Adds a sibling element before or after this one in the dom.Element prependSibling(Element e)dittoElement appendChild(Element e)Appends the given element to this one. If it already has a parent, it is removed from that tree and moved to this one.Element insertBefore(in Element where, Element what)Inserts the second element to this node, right before the first paramElement insertAfter(in Element where, Element what)Inserts the given element `what` as a sibling of the `this` element, after the element `where` in the parent node.Element swapNode(Element child, Element replacement)swaps one child for a new thing. Returns the old child which is now parentless.Element[] childElements(string tagName = null) @propertyReturns child elements which are of a tag type (excludes text, comments, etc.).Element[] appendHtml(string html) @scriptableAppends the given html to the element, returning the elements appendedinout(Element) self() inout pure @nogc nothrow @safe scope returnReturns `this` for use inside `with` expressions.void insertChildAfter(Element child, Element where)Inserts a child under this element after the element `where`.Element[] stealChildren(Element e, Element position = null)Reparents all the child elements of `e` to `this`, leaving `e` childless.Element prependChild(Element e)Puts the current element first in our children list. The given element must not have a parent already.string innerHTML(Appender!string where = appender!string()) @property constReturns a string containing all child elements, formatted such that it could be pasted into an XML file.Element innerHTML(string html, bool strict = false) @propertyTakes some html and replaces the element's children with the tree made from the string.Element[] outerHTML(string html) @propertyReplaces this node with the given html string, which is parsedvoid innerRawSource(string rawSource) @propertyThis sets the inner content of the element without trying to parse it. You can inject any code in there; this serves as an escape hatch from the dom.Element replaceChild(Element find, Element replace)Replaces the element `find`, which must be a child of `this`, with the element `replace`, which must have no parent.void replaceChild(Element find, Element[] replace)Replaces the given element with a whole group.Element removeChild(Element c)Removes the given child from this list.Element[] removeChildren()This removes all the children from this element, returning the old list.string visibleText() constGets the element's visible text, similar to how it would look assuming the document was HTML being displayed by a browser. This means it will attempt whitespace normalization (unless it is a `<pre>...void innerText(string text) @scriptable @propertySets the inside text, replacing all children. You don't have to worry about entity encoding.void outerText(string text) @propertyStrips this node out of the document, replacing it with the given textstring outerText() @property constSame result as innerText; the tag with all inner tags stripped outElement cloned() @propertyThis is a full clone of the element. Alias for cloneNode(true) now. Don't extend it.Element cloneNode(bool deepClone)Clones the node. If deepClone is true, clone all inner tags too. If false, only do this tag (and its attributes), but it will have no contents.string nodeValue() constW3C DOM interface. Only really meaningful on [TextNode] instances, but the interface is present on the base class.string toString() constTurns the whole element, including tag, attributes, and children, into a string which could be pasted into an XML file.bool isEmpty() constReturns if the node would be printed to string as `<tag />` or `<tag></tag>`. In other words, if it has no non-empty text nodes and no element nodes. Please note that whitespace text nodes are NOT ...string toPrettyStringIndent(bool insertComments, int indentationLevel, string indentWith) conststring toPrettyString(bool insertComments = false, int indentationLevel = 0, string indentWith = "\t") constWrites out with formatting. Be warned: formatting changes the contents. Use ONLY for eyeball debugging.string toPrettyStringImpl(bool insertComments = false, int indentationLevel = 0, string indentWith = "\t") conststring writeToAppender(Appender!string where = appender!string()) constThis is the actual implementation used by toString. You can pass it a preallocated buffer to save some time. Note: the ordering of attributes in the string is undefined. Returns the string it creates.Element addField(string label, string name, string type = "text", FormFieldOptions fieldOptions = FormFieldOptions.none)Adds a form field to this element, normally a `<input>` but `type` can also be `"textarea"`.Element addField(Element label, string name, string type = "text", FormFieldOptions fieldOptions = FormFieldOptions.none)dittoElement addField(string label, string name, FormFieldOptions fieldOptions)dittoElement addField(string label, string name, string[string] options, FormFieldOptions fieldOptions = FormFieldOptions.none)dittoElement addSubmitButton(string label = null)dittothis(Document _parentDocument, string _tagName, string[string] _attributes = null, bool _selfClosed = false)Generally, you don't want to call this yourself - use Element.make or document.createElement instead.this(string _tagName, string[string] _attributes = null, const string[] selfClosedElements = htmlSelfClosedElements)Convenience constructor when you don't care about the parentDocument. Note this might break things on the document. Note also that without a parent document, elements are always in strict, case-sen...ClassListHelperThe object [classList] returns.Specializes Document for handling generic XML. (always uses strict mode, uses xml mime type and file header)
<script> and <style> that [Document]
does for HTML. To get the old behavior back, add , true to your constructor call. Group: core_functionality
An option type that propagates null. See: Element.optionSelector Group: implementations
SomeElementType elementauto opDispatch(string method, T...)(T args)Forwards to the element, wit a null check inserted that propagates null.this(SomeElementType ele)A collection of elements which forwards methods to the children. Group: implementations
Element[] elementsElementCollection opIndex(string selector)Element[] opSlice()if you slice it, give the underlying array for easy forwarding of the collection to range expecting algorithms or looping over.void popFront()And input range primitives so we can foreach over thisbool empty()dittostring collect(string method)(string separator = "")Collects strings from the collection, concatenating them together Kinda like running reduce and ~= on it.ElementCollection opDispatch(string name, T...)(T t)Forward method calls to each individual [Element|element] of the collection returns this so it can be chained.ElementCollection wrapIn(Element what)Calls [Element.wrapIn] on each member of the collection, but clones the argument `what` for each one.ElementCollection opBinary(string op : "~")(ElementCollection rhs)Concatenates two ElementCollection together.Proxy object for attributes which will replace the main opDispatch eventually Group: implementations
private Element _elementstring set(string name, string value)Sets a `value` for attribute with `name`. If the attribute doesn't exist, this will create it, even if `value` is `null`.auto opBinaryRight(string op : "in")(string name) constProvides support for testing presence of an attribute with the `in` operator.private InternalAttribute * nextprivate uint totalLengthprivate ushort keyLengthprivate char[0] charsInternalAttribute * make(in char[] key, in char[] value) staticprivate InternalAttribute * attributesstring opIndex(scope const char[] key) conststring get(scope const char[] key, string returnedIfKeyNotFound = null) constbool opBinaryRight(string op : "in")(scope const char[] key) constvoid opAssign(string[string] aa) @trustedvoid remove(scope const char[] key) @trustedvoid opIndexAssign(scope const char[] value, scope const char[] key) @trustedstring toString()This might belong in another module, but it represents a file with a mime type and some data. Document implements this interface with type = text/html (see Document.contentType for more info) and data = document.toString, so you can return Documents anywhere web.d expects FileResources. Group: bonus_functionality
string contentType() @property const;the content-type of the file. e.g. "text/html; charset=utf-8" or "image/png". Group: bonus_functionality
. Group: core_functionality
string toPrettyStringImpl(bool insertComments, int indentationLevel, string indentWith) const. Group: implementations
string source.string toPrettyStringImpl(bool, int, string) const. Group: implementations
string source.. Group: implementations
string source.. Group: implementations
string source.. Group: implementations
string contents.string opDispatch(string name)(string v = null) if(0)string toPrettyStringImpl(bool insertComments = false, int indentationLevel = 0, string indentWith = "\t") constThere are subclasses of Element offering improved helper functions for the element in HTML. Represents a HTML link. This provides some convenience methods for manipulating query strings, but otherwise is sthe same Element interface.
Please note this object may not be used for all <a> tags. Group: implementations
string getValue(string name)This gets a variable from the URL's query string.string[string] variablesHash()void updateQueryString(string[string] vars)Replaces all the stuff after a ? in the link at once with the given assoc array values.void setValue(string name, string variable)Sets or adds the variable with the given name to the given value It automatically URI encodes the values and takes care of the ? and &.void setValue(string name, string[] variable)void removeValue(string name)Removes the given variable from the query stringRepresents a HTML form. This slightly specializes Element to add a few more convenience methods for adding and extracting form data.
Please note this object may not be used for all <form> tags. Group: implementations
Element addField(string label, string name, string type = "text", FormFieldOptions fieldOptions = FormFieldOptions.none)Overrides of the base class implementations that more confirm to my conventions when writing form html.Element addField(string label, string name, FormFieldOptions fieldOptions)dittoElement addField(string label, string name, string[string] options, FormFieldOptions fieldOptions = FormFieldOptions.none)dittovoid setValue(string field, string value)dittovoid setValue(string name, string[] variable)void setValue(string field, string value, bool makeNew)Set's the form field's value. For input boxes, this sets the value attribute. For textareas, it sets the innerText. For radio boxes and select boxes, it removes the checked/selected attribute from ...void addValueArray(string key, string[] arrayOfValues)This takes an array of strings and adds hidden <input> elements for each one of them. Unlike setValue, it makes no attempt to find and modify existing elements in the form to the new values.string getValue(string field)Gets the value of the field; what would be given if it submitted right now. (so it handles select boxes and radio buttons too). For checkboxes, if a value isn't given, but it is checked, it returns...string getPostableData()Returns the form's contents in application/x-www-form-urlencoded format.Element addInput(string name, string value, string type = "hidden")Adds a new INPUT field to the end of the form with the given attributes.void removeField(string name)Removes the given field from the form. It finds the element and knocks it right out.Represents a HTML table. Has some convenience methods for working with tabular data. Group: implementations
Element th(T)(T t)Creates an element with the given type and content. The argument can be an Element, Html, or other data which is converted to text with `to!string`Element appendHeaderRow(T...)(T t)Passes each argument to the [th] method for `appendHeaderRow` or [td] method for the others, appends them all to the `<tbody>` element for `appendRow`, `<thead>` element for `appendHeaderRow`, or a...Element appendFooterRow(T...)(T t)dittovoid addColumnClasses(string[] classes...)Takes each argument as a class name and calls [Element.addClass] for each element in the column associated with that index.Element appendRowInternal(T...)(string innerType, string findType, T t)Element captionElement()Returns the `<caption>` element of the table, creating one if it isn't there.string caption() @propertyReturns or sets the text inside the `<caption>` element, creating that element if it isnt' there.Represents a table row element - a
Represents anything that can be a table cell -
This is thrown on parse errors. Group: implementations
this(string message, string file = __FILE__, size_t line = __LINE__).This is used when you are using one of the require variants of navigation, and no matching element can be found in the tree. Group: implementations
Element searchContextThe html struct is used to differentiate between regular text nodes and html in certain functions
Easiest way to construct it is like this: auto html = Html("<p>hello</p>"); Group: core_functionality
string sourceThis string holds the actual html. Use it to retrieve the contents.DomMutationOperations operationElement targetElement relatedElement related2string relatedStringstring relatedString2ditto
string tagNameFilterstring[] attributesPresentstring[2][] attributesEqualstring[2][] attributesStartsWithstring[2][] attributesEndsWithstring[2][] attributesIncludesSeparatedBySpacesstring[2][] attributesIncludesSeparatedByDashesstring[2][] attributesIncludestring[2][] attributesNotEqualstring[] hasSelectorsstring[] notSelectorsstring[] isSelectorsstring[] whereSelectorsParsedNth[] nthOfTypeParsedNth[] nthLastOfTypeParsedNth[] nthChildbool firstChildbool lastChildbool firstOfTypebool lastOfTypebool emptyElementbool whitespaceOnlybool oddChildbool evenChildbool scopeElementbool rootElementint separationbool isCleanSlateExceptSeparation()string toString().bool matchElement(Element e, Element scopeElementNow = null)Returns true if the given element matches this partint multiplierint adderstring ofstring toString()void consumeWhitespace(ref string text)int parseNumber(ref string text)this(string text)Represents a parsed CSS selector. You never have to use this directly, but you can if you know it is going to be reused a lot to avoid a bit of repeat parsing.
bool matchesElement(Element e, Element relativeTo = null)Returns true if the given element matches this selector, considered relative to an arbitrary element.Element[] getMatchingElements(Element start, Element relativeTo = null)Reciprocal of [Element.querySelectorAll]auto getMatchingElementsLazy(Element start, Element relativeTo = null)Like [getMatchingElements], but returns a lazy range. Be careful about mutating the dom as you iterate through this.string toString()Returns the string this was built fromstring parsedToString()Returns a string from the parsed resultthis(string cssSelector)Parses the selector string and constructs the usable structure..
SelectorPart[] parts.string toString().Element[] getElements(Element start, Element relativeTo = null).bool matchElement(Element e, Element relativeTo = null)If relativeTo == null, it assumes the root of the parent document.This is probably not useful to you unless you're writing a browser or something like that. It represents a computed style, like what the browser gives you after applying stylesheets, inline styles, and html attributes. From here, you can start to make a layout engine for the box model and have a css aware browser.
string originatingRuleSpecificity originatingSpecificityProperty[] properties.Specificity getSpecificityOfRule(string rule).string opDispatch(string nameGiven)(string value = null) if(nameGiven != "popFront").string getValue(string name)takes dash style namestring setValue(string name, string value, Specificity newSpecificity, bool explicit = true)takes dash style namevoid expandQuadShort(string name, string value, Specificity specificity)void expandShortForm(Property p, Specificity specificity).string toString().this(string rule, string content).Property.This probably isn't useful, unless you're writing a browser or something like that. You might want to look at arsd.html for css macro, nesting, etc., or just use standard css as text.
The idea, however, is to represent a kind of CSS object model, complete with specificity, that you can apply to your documents to build the complete computedStyle object.
CssStyle[] rules.this(string source).This is the lazy range that walks the tree for you. It tries to go in the lexical order of the source: node, then children from first to last, each recursively.
void popFront().void currentKilled()You should call this when you remove an element from the tree. It then doesn't recurse into that node and adjusts the current position, keeping the range stable.Currentstring patternthis is a regex pattern used to validate the fieldbool isRequiredmust the field be filled in? Even with a regex, it can be submitted blank if this is false.string placeholderthis is displayed as an example to the userFormFieldOptions required() staticFormFieldOptions regex(string pattern, bool required = false) staticFormFieldOptions fromElement(Element e) staticthis(ElementStream range, bool delegate(Element e) filter)bool isConvenientAttribute(string name)bool canNestElementsInHtml(string parentTagName, string childTagName)Element[] findComments(Document document, string txt)finds comments that match the given txt. Case insensitive, strips whitespace. Group: core_functionalitystring unCamelCase(string a)Converts a camel cased propertyName to a css style dashed property-nameT require(T = Element, string file = __FILE__, int line = __LINE__)(Element e) if(is(T : Element))You can use this to do an easy null check or a dynamic cast+null check on any element. Group: core_functionalitystring htmlEntitiesEncode(string data, Appender!string output = appender!string(), bool encodeNonAscii = true)Given text, encode all html entities on it - &, <, >, and ". This function also encodes all 8 bit characters as entities, thus ensuring the resultant text will work even if your charset isn't set r...string xmlEntitiesEncode(string data)An alias for htmlEntitiesEncode; it works for xml too Group: core_functionalitydchar parseEntity(in dchar[] entity)This helper function is used for decoding html entities. It has a hard-coded list of entities and characters. Group: core_functionalitystring htmlEntitiesDecode(string data, bool strict = false)This takes a string of raw HTML and decodes the entities into a nice D utf-8 string. By default, it uses loose mode - it will try to return a useful string from garbage input too. Set the second pa...Element[] getElementsBySelectorParts(Element start, SelectorPart[] parts, Element scopeElementNow = null)dittostring cssUrl(string url)sizediff_t indexOfBytes(immutable(ubyte)[] haystack, immutable(ubyte)[] needle)bool isInArray(T)(T item, T[] arr)string normalizeWhitespace(string text, bool stripLeadingAndTrailing = true)Normalizes the whitespace in the given text according to HTML rules.bool allAreInlineHtml(const(Element)[] children, const string[] inlineElements)string[] htmlSelfClosedElementsstring[] htmlRawSourceElementsstring[] htmlInlineElementsstring[] selectorTokens.
This delegate is called if you call Element.computedStyle to attach an object to the element that holds stylesheet information. You can rebind it to something else to return a subclass if you want to hold more per-element extension data than the normal computed style object holds (e.g. layout info as well).
The default is return new CssStyle(null, element.style);
string[] availableEntitiesdchar[] availableEntitiesValues