Web Application Development - DOM

1361 字
7 分钟
Web Application Development - DOM

The Document Object Model#

  • Last lecture you saw the basics of control flow programs in JavaScript.
  • We now need to learn how to manipulate the web page and browser using JavaScript.
  • This is done through a series of built-in objects. The specifications of these objects are called the DOM (Document Object Model) and BOM (Browser Object Model).
  • The BOM is not officially standardised, although there are standards for most browsers. The DOM is standardised as part of HTML5.

The Browser Object Model#

  • The Browser Object model covers all available data about the browser other than the actual page.
  • It provides:
    • window: holds all your declared variables. Also can get the size of the window (or tab). May be able to open or move windows but this functionality is often restricted. Also displays alerts and prompts and manages timing.
    • screen: contains the height, width and color depth of the screen; however, these are better accessed elsewhere.
    • location: accesses the entered web address.
    • history: can simulate clicking Back and Forward on the browser. Cannot access previously visited URLs.
    • navigator: identifies the browser and OS.

Document Object#

  • The document object is built based on the document object model.
  • It provides access to a database of all other elements on the HTML page.
  • When you extract an element from the database, it is returned in the form of an object, with properties and methods as appropriate for that type of element.
  • By calling or changing these properties or methods, you can manipulate the element.

Accessing the document#

<html>
<head><title>Example</title></head>
<body>
<img ID="menu" src="menu.jpg">
</body>
</html>

This img element has the ID menu, so we can get a reference to it with document.GetElementById("menu").


<html>
<head><title>Example</title></head>
<body>
<form name=“login”>
<input ID=“username” type=text>
</form>
</body>
</html>

This input element has ID username, so we can get a reference to it with document.GetElementById("username"). IDs have to be unique across the whole document, so it does not matter that it is nested within a form.


<html>
<head><title>Example</title></head>
<body>
<form id="login">
<input type=text>
</form>
</body>
</html>

You can also get all elements of a particular type. Doing so returns a list, to allow for the possibility of there being more than one.

document.GetElementsByTagName("input")
Note

id is unique, but class and tag are not.

Only GetElementsById gets one element, others get collection.

HTML tree#

  • The document object model is built in a tree structure, as with the HTML document itself.
  • Traditionally, positions in the tree are described using terms taken from family trees, even though these are not always absolutely accurate.

Accessing the document#

<html>
<head><title>Example</title></head>
<body>
<p name="username">Username:</p>
<form name="login">
<input name="username" type="text">
</form>
<p name="password">Password:</p>
<form name="login2">
<input name="password" type="hidden">
</form>
</body>
</html>

<html>
<head><title>Example</title></head>
<body>
<p name="username">Username:</p>
<form name="login">
<input name="username" type="text">
</form>
<p name="password">Password:</p>
<form name="login2">
<input name="password" type="hidden">
</form>
</body>
</html>

This p element is a child of the body.

The body is the parent of the p.

Note

Tag p here still has child —— the text.


<html>
<head><title>Example</title></head>
<body>
<p name="username">Username:</p>
<form name="login">
<input name="username" type="text">
</form>
<p name="password">Password:</p>
<form name="login2">
<input name="password" type="hidden">
</form>
</body>
</html>

This input element is a child of the form.

The form is the parent of the input.

The body is not the parent of the input.

The input is not a child of the body.

The input and the form are not siblings.

The body is not the parent of the input.

The body is the ancestor of the input.

The input is not a child of the body.

The input is the descendant of the body.


In the DOM, plain text is considered another form of child, in the same way that another element would be.

The text “username:” is a child of the p element.


<body>
<p>
My name is <b>Bob</b> and I am
<i>here</i>.
</p>
</body>

(This is why it is important to nest your elements correctly!)


<html>
<head><title>Example</title></head>
<body>
<div id="upper"><p>Hi!</p></div>
<div id="lower"><p>Lo!</p></div>
</body>
</html>

Calling getElementsByTagName on elements other than the top-level document will get only descendants of that element. document.getElementById("upper").getElementsByTagName("p") will get only the p tag containing “Hi!”.


<html>
<head><title>Example</title></head>
<body>
<div class=“item”>Item 1</div>
<div class=“item lite”>Item 2</div>
</body>
</html>

You can also get lists of items based on their CSS style class. Any object which is a member of the named class will be included in the resulting list, even if it is a member of other classes as well.

document.GetElementsByClassName("item")

Finding HTML elements#

  • Ideally you should structure your HTML to make finding elements to be altered via JavaScript as easy as possible.
    • If one particular element needs to be found, give it an ID.
    • If one particular set of elements are manipulated together, make them the children of an element with a particular ID, or give them the same CSS class.

Using Element Objects#

  • Once you have obtained an HTML element object you can store it in a variable:
let top = document.getElementById(“main”);
  • You can then call methods and properties on that object to alter the web page.
  • You can also access other parts of the tree based on the element. Every element has these properties:
    • parentNode: the parent element
    • childNodes: an array of the child elements
    • firstChild, lastChild
    • nextSibling, previousSibling

The DOM tree and CSS#

  • Although we did not mention it at the time, you can also use the DOM tree when writing CSS files.

  • nav {...} Affects all nav elements

  • nav p {...} Affects all p elements that are descendents of nav elements

  • nav > p {...} Affects all p elements that are children of nav elements

  • nav ~ p {...} Affects all p elements that are later siblings of nav elements

Selector API#

  • You can also use CSS style specifications to obtain sets of elements in JavaScript.
  • The function document.querySelectorAll can be called with a CSS-style selector as a string. It returns the list of all elements matching that selector.
  • For example:
let clickedLinks = document.querySelectorAll ("nav > a:visited");

Manipulating element objects#

  • Once you have an element object, you can modify the object to modify the web page.
  • The simplest case is changing an attribute.
  • For every attribute that an HTML element has or could legally have, there will be a property on the element object which you can read or write.

Accessing the document#

<html>
<head><title>Example</title></head>
<body>
<img id="menu" src="menu.jpg">
</body>
</html>

This image has an attribute called src. If we

let ourMenu=document.getElementById("menu");

our menu.src will contain the string menu.jpg. The src attribute on an image specifies the filename of the image. So by changing this attribute in our script, we could alter the image, make it animate, etc.


<html>
<head><title>Example</title></head>
<body>
<form id="login">
<input id="username" type=text>
</form>
</body>
</html>

This element doesn’t have a value attribute – but it is possible for an HTML input element to have one. The rules of HTML specify that this attribute holds the contents of the element – ie, the text appearing within the input box. Thus, our JavaScript program can read this as

document.getElementById("username").value

<html>
<head><title>Example</title></head>
<body>
<div id="one" class="moose">Moose!</div>
</body>
</html>

You can alter the CSS attributes of an element by using its style property. For example, to change the background color of this div, we can change

document.getElementById("one").style.backgroundColor

Note that doing this is equivalent to inserting a style attribute in the HTML that overrides that aspect of the class; other elements of class moose will not be affected.


<html>
<head><title>Example</title></head>
<body>
<div id="one" data-price="14.99">Our new product</div>
</body>
</html>

HTML5 allows data- attributes to be used to store arbitrary data inline in an HTML5 file. The names of data attributes must begin with data- but thereafter may be anything.
The values of these attributes can then be accessed, eg:

document.getElementById("one").dataset.price

Manipulating text and content#

  • You can change the entire content of a tag as text by altering its innerHTML property. However, this will overwrite everything inside the tag and force the browser to recalculate the DOM. It may be better to use fields.
  • You can also manipulate the tree to alter the page directly by calling methods on an element object.

Altering the HTML tree#

<body onLoad="start()">
<p id="base">My name is Sir Cunningham and I am
<i>very smart</i>.</p>
<button onClick="change()">Change</button>
</body>


function change() {
let base=document.getElementById("base");
let italics=base.getElementsByTagName("i")[0]; italics.remove();
let newNode=document.createElement("i");
let newText=document.createTextNode("a bit of a wally, really");
newNode.appendChild(newText);
base.insertBefore(newNode, base.lastChild);
}

let base=document.getElementById("base");
let italics=base.getElementsByTagName("i")[0];
italics.remove();


let newNode=document.createElement("i");
let newText=document.createTextNode("a bit of a wally, really");
newNode.appendChild(newText);
base.insertBefore(newNode, base.lastChild);

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!

赞助
Web Application Development - DOM
https://firefly.anka2.top/posts/obu/level5/semester2/wad/week4/lecture/
作者
🐦‍🔥不死鸟Anka
发布于
2026-03-30
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
A-n-k-a
Over the Frontier / Into the Front
看这里~
合作翻译官绝赞招募中!
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
59
分类
6
标签
20
总字数
550,118
运行时长
0
最后活动
0 天前

目录