The Document Tree
A web page or document written in X(HTML) is made up by a series of elements which follow each other in the page code. This sequence of elements is referred to as the Document Tree and the way the different elements which make up the document tree relate to each other is an important concept to understand.
The position of an element compared to the other elements in the document is defined by a series of relationships which are explained here using the following simple document tree for illustration purposes:
- Parent element - Each element in the document tree has exactly one parent apart from the root element which has no parent element,
<html>is the root element in this example and in all XHTML documents and has no parent. In our example the
<html>element is the parent of the
<head>element is the parent of the
<title>element and the
<body>element is the parent of the
- Child element - An element B is called the child of another element A if, and only if, element A is the parent of element B. The
<head>elements above are both children of the
<html>element and the
<title>element is a child of the
- Descendant - An element B is called a descendant of element A if either, B is a child of A or, B is the child of another element C which is a descendant of element A.
In our element tree all the other elements are descendants of the
<html>element and the
<li>elements are also descendants of the
- Ancestor - An element A is an ancestor of element B if, and only if B is a descendant of A, in the above
<html>is an ancestor to all the other elements and
<body>is an ancestor of the
- Sibling - An element B is a sibling of another element C if both elements share the same parent. B can be either a preceding sibling or a following sibling depending
on whether it comes before (preceding) or after (following) element C in the document tree. In our tree the
<ul>elements are siblings as they are all children of the
<body>element and the
<body>elements are siblings as they both have
<html>as their parent.
- Preceding element - Element A is called a preceding element of element B if either, A is an ancestor of B or, A is a preceding sibling of B. In the above tree the
<head>element is a preceding element in relation to the
<body>element and the first
<p>element is a preceding element in relation to the
<ul>element and second
- Following element - An element B is a following element of an element A if A is a preceding element of element B.
It is especially important to have a firm grasp of the document tree in relation to CSS selectors, many of which are applied to elements according to their relationship to other elements in the document tree - such as children, siblings and descendants. In addition to this the use of the CSS position, top, right, bottom and left properties can depend on element relationships within the document tree.