# Document Object Model (DOM) 文档对象模型
- Object representation of a HTML or XML Document in memory
内存中 HTML 或 XML 文档的对象表示 - All elements are represented by objects
所有元素都由对象表示 - DOM is an API that can be used in many languages
DOM 是一种可以在多种语言中使用的 API - JavaScript uses DOM scripting to modify the elements on a page
JavaScript 使用 DOM 脚本来修改页面上的元素 - DOM is a collection of nodes in a tree
DOM 是树中节点的集合 - Also provides standard methods to traverse the DOM, access elements and modify elements
还提供了遍历 DOM、访问元素和修改的标准方法元素
# DOM Selection
- Accessing the DOM elements
Use methods of the document object
使用文档对象的方法 - Most common by
id
let a = document.getElementById("elementid");
- Can also access by
class
,tag
,selector
- Use the
Element.getAttribute("src");
method to get an attribute's value from an element. Use thesetAttribute
to set or change one. - Set of methods to manipulate DOM objects.
https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model
# By Id
always will return one DOM element since id needs to be unique on the page.
总是会返回一个 DOM 元素,因为 id 在页面上必须是唯一的。
var element = document.getElementById('someId'); |
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
# By Class Name
returns an HTMLCollection
var elements = document.getElementsByClassName('classnames'); |
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
# By Tag Name
returns an HTMLCollection
var elements = document.getElementsByTagName('tagname'); |
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
# By Selector
returns one element or a NodeList of element objects, uses CSS style selectors
返回一个使用 CSS 样式选择器的元素或元素对象的 NodeList
var element = document.querySelector('css selector string'); | |
var elementList = document.querySelectorAll('css selector string'); |
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
# DOM Event Handling
Three Methods – 3rd method is the most preferred way
- As attribute on HTML element 作为 HTML 元素的属性
- As a method attached to a DOM object 作为附加到 DOM 对象的方法
- Using the add event handler method of an object 使用对象的 add 事件处理程序方法
最优选
# As attribute on HTML element
作为 HTML 元素的属性
Not suggested, mixes JavaScript and HTML structure in the HTML markup.
不建议,在 HTML 标记中混合使用 JavaScript 和 HTML 结构。Uses the attribute that pertains to the particular event. Usually in the form of
on + something
. Click event isonclick
.
使用与特定事件相关的属性。通常采用on + something
形式。点击事件是onclick
。JavaScript code is embedded in the event attribute.
JavaScript 代码嵌入在事件属性中。
<div onclick="alert('I was clicked')">click me</div> |
# As a method attached to a DOM object
作为附加到 DOM 对象的方法
Not suggested, while it separates the event handler logic from the HTML markup you still have limitations.
不建议,虽然它将事件处理程序逻辑与 HTML 标记分开,但仍然有限制。Can only apply one event handler to an element using this method.
只能将一个事件处理程序应用于使用此方法的元素。JavaScript function is assigned to the event name property on the element. Click is
onclick
.
JavaScript 函数被分配给元素上的事件名称属性。点击是onclick
。
<div id=“aButton”>Click Me</div> |
document.getElementById('aButton').onclick = function(){ | |
//code in this block | |
}; |
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Event_handlers
# Using the add event listener method of a object
This is the preferred modern standards compliant method. This is what I want to see unless you have good reason to use the other two and can explain why.
这是首选的符合现代标准的方法。除非有充分的理由使用其他两个并可以解释原因。This allows you to bind multiple handlers on the same element to listen for the same event.
允许在同一元素上绑定多个处理程序以侦听同一事件。Event types are without the word “on” before them. Click is
click
.
事件类型前面没有 “on” 一词。点击就是click
。element.addEventListener("click", myFunction, false);
https://developer.mozilla.org/en-US/docs/Web/Events
Make sure you pass the function object, not execute the function. Notice no parenthesis.
确保传递函数对象,而不是执行函数。注意没有括号。
Or declare an anonymous inline function.
或者声明一个匿名内联函数。
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
# DOM Element Manipulation
DOM elements have a property,
innerHTML
, that sets or gets the HTML syntax that describes all the element's children.
DOM 元素有一个属性,innerHTML
,设置或获取描述所有子元素的 HTML 语法。DOM elements also have an
innerText
property that can be used if the inner content is only text with no HTML syntax. HTML will not be parsed and inserted as plain text.
DOM 元素还有一个innerText
属性,如果内部内容只是没有 HTML 的文本,则可以使用该属性句法。HTML 不会作为纯文本被解析和插入。
let content = element.innerHTML; | |
element.innerHTML = '<p>New HTML</p>'; | |
let content = element.innerText; | |
element.innerText = 'this is some text'; |
innerHTML
can introduce security concerns so you need to use it carefully.innerHTML
会引入安全问题,因此您需要谨慎使用它。- There is also a
textContent
property that is very similar toinnerText
. It differs in that ittextContent
will also get hidden text text content like a<script>
tag not just visible text.
还有一个与innerText
非常相似的textContent
属性。它的不同之处在于它textContent
也会得到隐藏文本文本内容,例如<script>
标签,而不仅仅是可见文本。
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent#differences_from_innertext
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText
# Getting values from form fields
从表单域中获取值
# Most basic is the input
element
This could be of type
text
,button
,checkbox
,radio
, and others that use the HTML<input>
element form control.
最基本的是输入元素。这可以是文本、按钮、复选框、单选和其他使用 HTML<input>
元素表单控件的。https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_<input>_types
Many properties to interact with the control. Very important one that applies to all types of input controls is value.
许多与控件交互的属性。非常重要的一个适用于所有类型的输入控件是值。Gets or Sets the value element.value = '5';
let result = element.value;
All values are get or set as a string from a form control. You must do any type conversions.
所有值都是从表单控件获取或设置为字符串。你必须做任何类型转换。
# Other popular form controls include
Select lists
https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement
See propertiesselectedIndex
,selectedOptions
,value
, and othersText Areas
https://developer.mozilla.org/en-US/docs/Web/API/HTMLTextAreaElement
Value property to get/set value same as input
# Helper methods you should looks into
辅助方法
Number()
- Object
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberOther built in global functions and objects
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_ObjectsBe very careful with the
parseInt()
function's behavior as demoed inclass
and theNaN
type.
对parseInt()
函数在类和NaN
类型中的行为要非常小心
# basic properties and methods
- Elements are the basic object everything descends from.
元素是一切都源自的基本对象。 - Review this link for basic properties and methods that apply to all elements.
查看此链接以了解基本信息适用于所有元素的属性和方法。
https://developer.mozilla.org/en-US/docs/Web/API/Element
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement - To properly create, move, delete, or modify elements you need to use properties or methods on the elements.
要正确创建、移动、删除或修改元素,您需要使用属性或元素上的方法。 - Changing Inline CSS Styles 更改内联 CSS 样式https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style
document.getElementById('anId').style.backgroundColor = '#000000';
CSS properties on style object usually use a camel case version of the name. Look it up if you can not figure it out.
样式对象上的 CSS 属性通常使用名称的驼峰式大小写版本。
# Methods used to create and insert an element
用于创建和插入元素的方法
- document.createElement()
https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement - document.createTextNode()
https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode - node.appendChild()
https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild - node.insertBefore()
https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore - node.removeChild()
https://developer.mozilla.org/en-US/docs/Web/API/Node/removeChild - node.replaceChild()
https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild
For example, to insert a new h3 in the body of an HTML page
例如,在 HTML 页面的正文中插入新的 h3
var head3 = document.createElement('h3'); | |
var headtext = document.createTextNode('This is my H3 headline'); | |
head3.appendChild(headtext); | |
var b = document.getElementsByTagName('body'); | |
b[0].appendChild(head3); |
# Basic DOM Demo
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Basic DOM Demo</title> | |
</head> | |
<body> | |
<!-- 1 --> | |
<h1 id="mainheadline">Basic DOM Demo</h1> | |
<button id="headlinebtn">Change Headline</button> | |
<hr> | |
<!-- 2 --> | |
<div> | |
<h2 id="headline2">Hello World!</h2> | |
<label>Name: <input id="nameIn" type="text" placeholder="Enter you name"></label> | |
<button id="helloBtn">Say Hello!</button> | |
</div> | |
<hr> | |
<!-- 3 --> | |
<div> | |
<h2>Square a number</h2> | |
<label>Enter a Number: <input id="numIn" type="text"></label> | |
<label>Square Value: <input id="sqVal" type="text" disabled></label> | |
<button id="sqBtn">Square my number!</button> | |
<button id="clearBtn">Clear Results</button> | |
</div> | |
<script> | |
// 1 | |
document.getElementById('headlinebtn').addEventListener('click', function(){ | |
document.getElementById('mainheadline').innerText = "Hello you changed the headline!"; | |
}); | |
// 2 | |
document.getElementById('helloBtn').addEventListener('click', function(){ | |
console.log('hello btn worked!'); | |
let myName = document.getElementById('nameIn').value.trim(); | |
if (myName === '') { | |
alert('You must enter a name!'); | |
} else { | |
document.getElementById('headline2').innerText = 'Hello ' + myName + '!'; | |
document.getElementById('nameIn').value = ''; | |
} | |
}); | |
// 3 | |
function squareMyNumber(){ | |
console.log('square my number works!'); | |
let myNumber = document.getElementById('numIn').value.trim(); | |
console.log(myNumber); | |
if (myNumber === '' || isNaN(Number(myNumber))) { | |
alert('You must enter a number to square!'); | |
document.getElementById('numIn').value = ''; | |
document.getElementById('sqVal').value = ''; | |
} else { | |
document.getElementById('sqVal').value = myNumber * myNumber; | |
} | |
} | |
document.getElementById('sqBtn').addEventListener('click', squareMyNumber); | |
document.getElementById('clearBtn').addEventListener('click', function(){ | |
document.getElementById('numIn').value = ''; | |
document.getElementById('sqVal').value = ''; | |
}); | |
</script> | |
</body> | |
</html> |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>DOM Event Handler Demo</title> | |
<style> | |
.btn { | |
padding: 25px; | |
background-color: red; | |
cursor: pointer; | |
} | |
</style> | |
</head> | |
<body> | |
<!-- Event Method #1 --> | |
<script> | |
function clickMethod1(text) { | |
console.log(text); | |
alert(text); | |
} | |
</script> | |
<div class="btn" onclick="clickMethod1('I was clicked with method 1!')">Click Me for Method 1!</div> | |
<hr> | |
<!-- Event Method #2 --> | |
<div class="btn" id="method2" style="background-color: blue;">Click Me for Method 2!</div> | |
<hr> | |
<script> | |
// document.getElementById('method2').onclick = function() { | |
// console.log('I was clicked with method 2'); | |
// alert('I was clicked with method 2!'); | |
// }; | |
function alertMe(text) { | |
console.log(text); | |
alert(text); | |
} | |
let el = document.getElementById('method2'); | |
el.onclick = function(evt){ | |
console.log(evt); | |
alertMe('I was clicked with method 2!'); | |
}; | |
</script> | |
<!-- Event Method #3 --> | |
<div class="btn" id="method3" style="background-color: green;">Click Me for Method 3!</div> | |
<script> | |
document.getElementById('method3').addEventListener('click', function(){ | |
console.log('I was clicked with method 3!'); | |
alert('I was clicked with method 3!'); | |
}); | |
function method3(evt){ | |
console.log(evt); | |
console.log('Second event of method 3'); | |
alert('second event on method 3'); | |
} | |
document.getElementById('method3').addEventListener('click', method3); | |
</script> | |
</body> | |
</html> |
# Quiz 4
You must use dot notation to access a property of an object in JavaScript.
The DOM selection method querySelector will return all the elements on a page that match the css selector passed to the method.
An object can not be the value of a property of an object in JavaScript.
Which of the answers is not a primitave value in JavaScript?
You access values from an HTML form control using the value DOM propery of the element.
Which JavaScript method of defining an event handler allow you to define multiple handlers for the same event on the same element?