arsd.dom

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.

History

The 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.

Types 52

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 subclass

If 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 mode

You 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

Fields
string _contentType
bool 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 _prolog
private bool prologWasSet
Element 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>s
Element[] piecesAfterRootstuff after the root, only stored in non-strict mode and not used in toString, but available in case you want it
bool loose.
void delegate(DomMutationEvent)[] eventObservers
Methods
inout(Document) asDocument() inout
inout(Element) asElement() inout
void 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)ditto
void processNodeWhileParsing(Element parent, Element child)ditto
Document 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.
immutable(ubyte)[] getData() constimplementing the FileResource interface; it calls toString.
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)
private 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)
string title() @propertyGets the <title> element's innerText, if one exists
void title(string t) @propertySets the title of the page, creating a <title> element if needed.
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))ditto
SomeElementType requireSelector(SomeElementType = Element)(string selector, string file = __FILE__, size_t line = __LINE__) if( is(SomeElementType : Element))ditto
MaybeNullElement!SomeElementType optionSelector(SomeElementType = Element)(string selector, string file = __FILE__, size_t line = __LINE__) if(is(SomeElementType : Element))ditto
Element querySelector(string selector) @scriptableditto
Element[] querySelectorAll(string selector) @scriptableditto
Element[] getElementsBySelector(string selector)ditto
Element[] getElementsByTagName(string tag) @scriptableditto
Element[] getElementsByClassName(string tag) @scriptableditto
Element 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 colon
void 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[] forms().
Element createElement(string name).
Element createTextNode(string content).
Element findFirst(bool delegate(Element) doesItMatch).
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)ditto
string 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 debugging
Constructors
this(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.
interfaceDomParent
Methods
inout(Document) asDocument() inout;
inout(Element) asElement() inout;

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

Fields
Element[] children
string 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 _computedStyle
Methods
inout(Document) asDocument() inout
inout(Element) asElement() inout
ElementCollection opIndex(string selector)Returns a collection of elements by selector. See: [Document.opIndex]
Element opIndex(size_t index)Returns the child node with the particular index.
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 ids
MaybeNullElement!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.
string[] classes() @property constget all the classes on this element
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 removeClass(string c) @scriptableRemoves a particular class name.
bool hasClass(string c) constReturns whether the given class appears in this element.
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 addChild(string tagName, Element firstChild, string info2 = null)ditto
Element addChild(string tagName, in Html innerHtml, string info2 = null)ditto
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.
void 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.
string firstInnerText() constFetches the first consecutive text nodes concatenated together.
string directText() @propertyReturns the text directly under this element.
void directText(string text) @propertySets the direct text, without modifying other child nodes.
void setValue(string field, string value)
void setValue(string field, string[] value)
private 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) @property
inout(Element) parentNode() inoutReturns the parent node in the tree this element is attached to.
Element 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(string tagName, in Html innerHtml, string childInfo2 = null) staticditto
Element make(string tagName, Element child, string childInfo2 = null) staticditto
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 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 nextElementSibling() @propertyditto
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...
Element nextSibling(string tagName = null) @propertyditto
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/closest
Element[] querySelectorAll(string selector) @scriptableReturns elements that match the given CSS selector
Element[] getElementsByClassName(string cn)Returns child elements that have the given class name or tag name.
Element[] getElementsByTagName(string tag)ditto
string 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 chaining
bool hasAttribute(string name) @scriptableReturns if the attribute exists.
Element removeAttribute(string name) @scriptableRemoves the given attribute from the element.
string className() @property constGets or sets the class attribute's contents. Returns an empty string if it has no class.
Element className(string c) @propertyditto
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.
inout(Element[]) childNodes() @property inoutReturns the element's children.
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");`
AttributeSet attrs() @propertyGives dot/opIndex access to attributes
ElementStyle style() @propertyProvides both string and object style (like in Javascript) access to the style attribute.
ElementStyle style(string s) @propertyThis sets the style attribute with a string.
private 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 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 param
Element 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 appendText(string text) @scriptableAppends the given to the node.
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 appended
inout(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 innerHTML(Html html) @propertyditto
Element[] outerHTML(string html) @propertyReplaces this node with the given html string, which is parsed
string outerHTML() @propertyReturns all the html for this element, including the tag itself.
void 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 innerText() @scriptable @property constFetch the inside text, with all tags stripped out.
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>...
private string visibleTextHelper(bool pre) const
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 text
string outerText() @property constSame result as innerText; the tag with all inner tags stripped out
Element 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.
int nodeType() @property const.
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) const
string 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") const
string 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.
ElementStream tree() @propertyReturns a lazy range of all its children, recursively.
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)ditto
Element addField(string label, string name, FormFieldOptions fieldOptions)ditto
Element addField(string label, string name, string[string] options, FormFieldOptions fieldOptions = FormFieldOptions.none)ditto
Element addSubmitButton(string label = null)ditto
Constructors
this(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...
this(Document _parentDocument)
Nested Templates
ClassListHelperThe object [classList] returns.

Specializes Document for handling generic XML. (always uses strict mode, uses xml mime type and file header)

History

On December 16, 2022, it disabled the special case treatment of <script> and <style> that [Document]

does for HTML. To get the old behavior back, add , true to your constructor call. Group: core_functionality

Constructors
this(string data, bool enableHtmlHacks = false)Constructs a stricter-mode XML parser and parses the given data source.
this(Utf8Stream data, bool enableHtmlHacks = false)ditto
structMaybeNullElement(SomeElementType)

An option type that propagates null. See: Element.optionSelector Group: implementations

Fields
SomeElementType element
Methods
auto opDispatch(string method, T...)(T args)Forwards to the element, wit a null check inserted that propagates null.
Constructors
this(SomeElementType ele)

A collection of elements which forwards methods to the children. Group: implementations

Fields
Element[] elements
Methods
ElementCollection 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 this
Element front()ditto
bool empty()ditto
string 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.
Constructors
this(Element e, string selector)
structDataSet

A proxy object to do the Element class' dataset property. See Element.dataset for more info.

Do not create this object directly. Group: implementations

Fields
private Element _element
Methods
string set(string name, string value)
string get(string name) const
Constructors

Proxy object for attributes which will replace the main opDispatch eventually Group: implementations

Fields
private Element _element
Methods
string 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.
string get(string name) constReturns the value of attribute `name`, or `null` if doesn't exist
Constructors
this(Element e)Generally, you shouldn't create this yourself, since you can use [Element.attrs] instead.
private structInternalAttribute
Fields
private InternalAttribute * next
private uint totalLength
private ushort keyLength
private char[0] chars
Methods
inout(char)[] key() inout return
inout(char)[] value() inout return
InternalAttribute * make(in char[] key, in char[] value) static
Fields
private InternalAttribute * attributes
Methods
string opIndex(scope const char[] key) const
string get(scope const char[] key, string returnedIfKeyNotFound = null) const
private string[] keys() const
bool opBinaryRight(string op : "in")(scope const char[] key) const
private inout(InternalAttribute) * find(scope const char[] key) inout @trusted
void opAssign(string[string] aa) @trusted
void remove(scope const char[] key) @trusted
void opIndexAssign(scope const char[] value, scope const char[] key) @trusted
int opApply(int delegate(string key, string value) dg) const @trusted
string toString()
bool empty() const @trusted

for style, i want to be able to set it with a string like a plain attribute, but also be able to do properties Javascript style. Group: implementations

Fields
Element _element
string _attribute
string originalAttribute
Methods
string set(string name, string value)
string get(string name) const
string[string] rules() const
Constructors
this(Element parent)
Destructors
interfaceFileResource

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

Methods
string contentType() @property const;the content-type of the file. e.g. "text/html; charset=utf-8" or "image/png"
immutable(ubyte)[] getData() const;the data
string filename() @property const;filename, return null if none

. Group: bonus_functionality

Text = 3

. Group: core_functionality

Methods
string writeToAppender(Appender!string where = appender!string()) const.
string toPrettyStringImpl(bool insertComments, int indentationLevel, string indentWith) const
Constructors
this(Document _parentDocument).
this(Html html)Creates a document fragment from the given HTML. Note that the HTML is assumed to close all tags contained inside it.

Group: implementations

Methods
int nodeType() @property const.
Constructors
this(Document _parentDocument)

. Group: implementations

Fields
string source.
Methods
string nodeValue() const.
string writeToAppender(Appender!string where = appender!string()) const.
string toPrettyStringImpl(bool, int, string) const
RawSource cloneNode(bool deep)
Constructors
this(Document _parentDocument, string s).

Group: implementations

Fields
string source.
Methods
string nodeValue() const.
string writeToAppender(Appender!string where = appender!string()) const.
string toPrettyStringImpl(bool, int, string) const
Constructors
this(Document _parentDocument, string type)

. Group: implementations

Methods
PhpCode cloneNode(bool deep)
Constructors
this(Document _parentDocument, string s).

. Group: implementations

Methods
AspCode cloneNode(bool deep)
Constructors
this(Document _parentDocument, string s).

. Group: implementations

Fields
string source.
Methods
string nodeValue() const.
string writeToAppender(Appender!string where = appender!string()) const.
string toPrettyStringImpl(bool, int, string) const
Constructors
this(Document _parentDocument, string s).

. Group: implementations

Fields
string source.
Methods
string nodeValue() const.
string writeToAppender(Appender!string where = appender!string()) const.
string toPrettyStringImpl(bool, int, string) const
Constructors
this(Document _parentDocument, string s).

. Group: implementations

Fields
string source.
Methods
string nodeValue() const.
string writeToAppender(Appender!string where = appender!string()) const.
string toPrettyStringImpl(bool, int, string) const
Constructors
this(Document _parentDocument, string s).

. Group: implementations

Fields
string contents.
Methods
string opDispatch(string name)(string v = null) if(0)
TextNode fromUndecodedString(Document _parentDocument, string html) static.
TextNode cloneNode(bool deep) @property.
string nodeValue() const.
int nodeType() @property const.
string writeToAppender(Appender!string where = appender!string()) const.
string toPrettyStringImpl(bool insertComments = false, int indentationLevel = 0, string indentWith = "\t") const
Constructors
this(Document _parentDocument, string e).
this(string e)
classLink : Element

There 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

Methods
string getValue(string name)This gets a variable from the URL's query string.
private 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 string
Constructors
this(string href, string text)Constructs `<a href="that href">that text</a>`.
this(Document _parentDocument)ditto
classForm : Element

Represents 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

Methods
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)ditto
Element addField(string label, string name, string[string] options, FormFieldOptions fieldOptions = FormFieldOptions.none)ditto
void setValue(string field, string value)ditto
void 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[] getField(string name)Gets the actual elements with the given name
Element getLabel(string forId)Grabs the <label> with the given for tag, if there is one.
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.
Constructors
this(Document _parentDocument).
classTable : Element

Represents a HTML table. Has some convenience methods for working with tabular data. Group: implementations

Methods
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 td(T)(T t)ditto
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)ditto
Element appendRow(T...)(T t)ditto
void addColumnClasses(string[] classes...)Takes each argument as a class name and calls [Element.addClass] for each element in the column associated with that index.
private 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.
void caption(string text) @propertyditto
TableCell[][] getGrid(Element tablePortition = null)Gets the logical layout of the table as a rectangular grid of cells. It considers rowspan and colspan. A cell with a large span is represented in the grid by being referenced several times. The tab...
Constructors
this(Document _parentDocument)You can make this yourself but you'd generally get one of these object out of a html parse or [Element.make] call.

Represents a table row element - a Group: implementations

Constructors
this(Document _parentDocument).

Represents anything that can be a table cell - or html. Group: implementations

Methods
int rowspan() @property constGets and sets the row/colspan attributes as integers
int colspan() @property constditto
int rowspan(int i) @propertyditto
int colspan(int i) @propertyditto
Constructors
this(Document _parentDocument, string _tagName).
classMarkupException : Exception

This is thrown on parse errors. Group: implementations

Constructors
this(string message, string file = __FILE__, size_t line = __LINE__).
classElementNotFoundException : Exception

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

Fields
Element searchContext
Constructors
this(string type, string search, Element searchContext, string file = __FILE__, size_t line = __LINE__)type == kind of element you were looking for and search == a selector describing the search.
structHtml

The 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

Fields
string sourceThis string holds the actual html. Use it to retrieve the contents.
setAttribute
removeAttribute
appendChild
insertBefore
truncateChildren
removeChild
appendHtml
replaceHtml
appendText
replaceText
replaceTextOnly
Fields
Element target
Element related
Element related2
string relatedString
string relatedString2

ditto

Fields
string tagNameFilter
string[] attributesPresent
string[2][] attributesEqual
string[2][] attributesStartsWith
string[2][] attributesEndsWith
string[2][] attributesIncludesSeparatedBySpaces
string[2][] attributesIncludesSeparatedByDashes
string[2][] attributesInclude
string[2][] attributesNotEqual
string[] hasSelectors
string[] notSelectors
string[] isSelectors
string[] whereSelectors
ParsedNth[] nthOfType
ParsedNth[] nthLastOfType
ParsedNth[] nthChild
bool firstChild
bool lastChild
bool firstOfType
bool lastOfType
bool emptyElement
bool whitespaceOnly
bool oddChild
bool evenChild
bool scopeElement
bool rootElement
int separation
Methods
string toString().
bool matchElement(Element e, Element scopeElementNow = null)Returns true if the given element matches this part
structParsedNth
Fields
int multiplier
int adder
string of
Methods
string toString()
bool solvesFor(R)(R elements, Element e)
private void consumeWhitespace(ref string text)
private int parseNumber(ref string text)
Constructors
this(string text)
structSelector

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.

See Also

Fields
SelectorComponent[] components
string original
Methods
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 from
string parsedToString()Returns a string from the parsed result
Constructors
this(string cssSelector)Parses the selector string and constructs the usable structure.

.

Fields
SelectorPart[] parts.
Methods
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.
SelectorComponent fromString(string selector) static.

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.

Fields
string originatingRule
Specificity originatingSpecificity
Property[] properties.
Methods
Specificity getSpecificityOfRule(string rule).
string opDispatch(string nameGiven)(string value = null) if(nameGiven != "popFront").
string getValue(string name)takes dash style name
string setValue(string name, string value, Specificity newSpecificity, bool explicit = true)takes dash style name
private void expandQuadShort(string name, string value, Specificity specificity)
void expandShortForm(Property p, Specificity specificity).
string toString().
Constructors
this(string rule, string content).
Nested Templates
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.

Fields
CssStyle[] rules.
Methods
void apply(Document document)Run through the document and apply this stylesheet to it. The computedStyle member will be accurate after this call
Constructors
this(string source).
classStack(T)

This is kinda private; just a little utility container for use by the ElementStream class.

Fields
private T[] arr.
private size_t internalLength
private T[64] initialBuffer
Methods
void push(T t).
T pop().
T peek().
bool empty() @property.
Constructors

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.

Fields
private Current current
private Stack!(Current) stack
private bool isEmpty
Methods
Element front() @property.
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.
bool empty() @property.
Constructors
this(Element start)Use Element.tree instead.
Nested Templates
Current
Fields
string patternthis is a regex pattern used to validate the field
bool 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 user
Methods
FormFieldOptions none() @property static
FormFieldOptions regex(string pattern, bool required = false) static
aliasutf_encode = arsd.core.encodeUtf8
private structRetro(T)
Fields
T[] array
size_t pos
Methods
T front()
void popFront()
bool empty()
Constructors
this(T[] array)
private structAppender(T : string)
Fields
Impl * impl
Methods
void put(string s)
void put(char c)
void put(dchar c)
void reserve(size_t s)
string data()
Constructors
this(string start)
Nested Templates
Impl
private structLineSplitter
Fields
string s
size_t nextLineBreak
Methods
string front()
void popFront()
bool empty()
Constructors
this(string s)
private structElementStreamFilter
Fields
bool delegate(Element e) filter
Methods
void popFront()
bool empty()
Constructors
this(ElementStream range, bool delegate(Element e) filter)
private aliasindexOf = arsd.core.indexOf
private aliasstrip = arsd.core.stripInternal
private aliasstripRight = arsd.core.stripRightInternal
private aliasstartsWith = arsd.core.startsWith
private aliasendsWith = arsd.core.endsWith

Functions 42

fnbool isConvenientAttribute(string name)
fnbool canNestElementsInHtml(string parentTagName, string childTagName)
fnElement[] findComments(Document document, string txt)finds comments that match the given txt. Case insensitive, strips whitespace. Group: core_functionality
fnElement[] findComments(Element element, string txt)ditto
fnstring unCamelCase(string a)Converts a camel cased propertyName to a css style dashed property-name
fnstring camelCase(string a)Translates a css style property-name to a camel cased propertyName
fnT 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_functionality
fnstring 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...
fnstring xmlEntitiesEncode(string data)An alias for htmlEntitiesEncode; it works for xml too Group: core_functionality
fndchar 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_functionality
fnstring 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...
fnint intFromHex(string hex)helper function for decoding html entities
fnsizediff_t idToken(string str, sizediff_t position).
fnstring[] lexSelector(string selstr)Parts of the CSS selector implementation
fnElement[] getElementsBySelectorParts(Element start, SelectorPart[] parts, Element scopeElementNow = null)ditto
fnSelectorComponent[] parseSelectorString(string selector, bool caseSensitiveTags = true).
fnSelectorComponent parseSelector(string[] tokens, bool caseSensitiveTags = true).
fnstring cssUrl(string url)
fnsizediff_t indexOfBytes(immutable(ubyte)[] haystack, immutable(ubyte)[] needle)
private fnT[] insertAfter(T)(T[] arr, int position, T[] what)
fnbool isInArray(T)(T item, T[] arr)
private fnstring[string] aadup(in string[string] arr)
fnvoid fillForm(T)(Form form, T obj, string name)
fnstring normalizeWhitespace(string text, bool stripLeadingAndTrailing = true)Normalizes the whitespace in the given text according to HTML rules.
fnbool allAreInlineHtml(const(Element)[] children, const string[] inlineElements)
private fnbool isSimpleWhite(dchar c)
private fnlong min(long a, long b)
private fnlong max(long a, long b)
private fnAppender!string appender(T : string)()
private fnstring[] split(string s, string onWhat)
private fnstring replace(string s, string replaceWhat, string withThis)
private fnstring[] sortStrings(string[] obj) @trusted
private fnsize_t indexOf(string haystack, string needle, bool caseSensitive)
private fnstring to(T : string, F)(F f)
private fnint to(T : int, F)(F f)
private fnchar[] to(T : char[], F : dchar[])(F f)
private fnstring to(T : string, F : const(dchar)[])(F f)
private fnstring toLower(string s)
private fnstring toUpper(string s)

Variables 7

private varstring[] htmlSelfClosedElements
private varstring[] htmlRawSourceElements
private varstring[] htmlInlineElements
varstring[] selectorTokens

.

varCssStyle function(Element e) computedStyleFactory = & defaultComputedStyleFactory

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);

History

Added September 13, 2024 (dub v11.6)
varstring[] availableEntities
vardchar[] availableEntitiesValues