文檔對象模型dom
by Leonardo Maldonado
萊昂納多·馬爾多納多(Leonardo Maldonado)
什么是文檔對象模型,以及為什么應該知道如何使用它。 (What’s the Document Object Model, and why you should know how to use it.)
So, you’ve studied HTML, you’ve created your first tags, learned about CSS, made beautiful forms, amazing buttons, responsive pages and have started to show everyone how amazing all that was.
因此,您學習了HTML,創建了第一個標簽,了解了CSS,制作了精美的表格,使用了令人驚嘆的按鈕,并創建了響應式頁面,并開始向所有人展示這一切的驚人之處。
But then you decide that you want to take another step in your learning, and you’ve started wonder to yourself: “How can I add animation to my page? I wish that button made some animation on my page when I clicked it!”
但是隨后您決定要進一步學習,就開始對自己產生疑問:“如何向頁面添加動畫? 我希望當我單擊該按鈕時,該按鈕在頁面上產生一些動畫效果!”
Well, that’s where the DOM comes to solve your problem. You’ve probably heard a lot about it, but you might not know yet what is it and what problems it solves. So let’s dig in.
嗯,這就是DOM解決您問題的地方。 您可能已經聽說了很多,但是您可能還不知道它是什么以及它解決了什么問題。 因此,讓我們深入。
那么,什么是DOM? (So, what’s the DOM?)
Do you know all those cool animations that you see around, that make you think to yourself, “Wow, I wish I could make something like that”? All of those animations are made by manipulating the DOM. I will now explain to you how to start manipulating it and making your websites look cooler.
您是否知道周圍出現的所有很棒的動畫,這些動畫會讓您自己想:“哇,我希望我能做出類似的事情”? 所有這些動畫都是通過操縱DOM制作的。 現在,我將向您解釋如何開始操作它并使您的網站看起來更酷。
The DOM (Document Object Model) is an interface that represents how your HTML and XML documents are read by the browser. It allows a language (JavaScript) to manipulate, structure, and style your website. After the browser reads your HTML document, it creates a representational tree called the Document Object Model and defines how that tree can be accessed.
DOM(文檔對象模型)是一個界面,表示瀏覽器如何讀取HTML和XML文檔。 它允許使用一種語言(JavaScript)來操縱,構建和設置網站樣式。 瀏覽器讀取HTML文檔后,它將創建一個稱為“文檔對象模型”的代表性樹,并定義如何訪問該樹。
優點 (Advantages)
By manipulating the DOM, you have infinite possibilities. You can create applications that update the data of the page without needing a refresh. Also, you can create applications that are customizable by the user and then change the layout of the page without a refresh. You can drag, move, and delete elements.
通過操作DOM,您將擁有無限的可能性。 您可以創建無需刷新即可更新頁面數據的應用程序。 另外,您可以創建用戶可自定義的應用程序,然后無需刷新即可更改頁面的布局。 您可以拖動,移動和刪除元素。
As I said, you have infinite possibilities — you just need to use your creativity.
正如我所說,您擁有無限的可能性-您只需要發揮創造力即可。
瀏覽器表示 (Representation by the browser)
In the image above, we can see the representational tree and how it is created by the browser. In this example, we have four important elements that you’re gonna see a lot:
在上圖中,我們可以看到代表性樹以及瀏覽器如何創建它。 在此示例中,我們將看到四個重要的元素:
Document: It treats all the HTML documents.
Document :處理所有HTML文檔。
Elements: All the tags that are inside your HTML or XML turn into a DOM element.
元素 : HTML或XML內的所有標簽都將變成DOM元素。
Text: All the tags’ content.
文字 :所有標簽的內容。
Attributes: All the attributes from a specific HTML element. In the image, the attribute class=”hero” is an attribute from the <p> element.
屬性 :來自特定HTML元素的所有屬性。 在圖像中,屬性class =“ hero”是< p>元素的屬性。
操作DOM (Manipulating the DOM)
Now we’re getting to the best part: starting to manipulate the DOM. First, we’re gonna create an HTML element as an example to see some methods and how events work.
現在,我們進入了最好的部分:開始操作DOM。 首先,我們將創建一個HTML元素作為示例,以了解一些方法以及事件如何工作。
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Entendendo o DOM (Document Object Model)</title> </head> <body> <div class="container"> <h1><time>00:00:00</time></h1> <button id="start">Start</button> <button id="stop">Stop</button> <button id="reset">Reset</button> </div> </body> </html>
Very simple, right? Now we’re going to learn more about DOM methods: how to get our elements and start manipulating.
很簡單,對吧? 現在,我們將學習有關DOM方法的更多信息:如何獲取元素并開始進行操作。
方法 (Methods)
The DOM has a lot of methods. They are the connection between our nodes (elements) and events, something that we’ll learn more about later. I’m gonna show you some of the most important methods and how they’re used. There are a lot more methods that I’m not going to show you here, but you can see all of them methods here.
DOM有很多方法。 它們是節點(元素)和事件之間的連接,我們稍后將詳細了解。 我將向您展示一些最重要的方法以及它們的用法。 有很多更多的方法,我不是要你在這里展示,但你可以看到所有的這些方法在這里 。
getElementById() (getElementById())
This method returns the element that contains the name id passed. As we know, id’s should be unique, so it’s a very helpful method to get only the element you want.
此方法返回包含傳遞的名稱ID的元素。 眾所周知, id應該是唯一的,因此這是僅獲取所需元素的非常有用的方法。
var myStart = document.getElementsById('start');
myStart: Our variable name that looks similar to our id passed.
myStart :類似于我們傳遞的id的變量名。
start: id passed. And in case we do not have any id with that specific name, it returns null.
開始 : id已通過。 如果我們沒有該特定名稱的ID ,它會返回null 。
getElementsByClassName() (getElementsByClassName())
This method returns an HTMLCollection of all those elements containing the specific name class passed.
此方法返回所有包含傳遞的特定名稱類的元素的HTMLCollection 。
var myContainer = document.getElementsByClassName('container');
myContainer: Our variable name that looks similar to our class passed.
myContainer :我們的變量名稱,看起來與傳遞的類相似。
.container: our class passed. In case we do not have any class with that specific name, it returns null.
.container :我們班級通過。 如果我們沒有任何具有該特定名稱的類 ,則它返回null 。
getElementsByTagName() (getElementsByTagName())
This works the same way as those methods above: it also returns an HTMLCollection, but this time with a single difference: it returns all those elements with the tag name passed.
這與上述方法的工作方式相同:它還返回HTMLCollection,但是這次只是一個不同:它返回所有帶有已傳遞標簽名稱的元素 。
var buttons = document.getElementsByTagName('button');
buttons: Our variable name that looks similar to our tag name passed.
button :我們的變量名,看起來與傳遞的標簽名相似。
button: tag name that we want to get.
button :我們要獲取的標簽名稱 。
querySelector() (querySelector())
It returns the first element that has the specific CSS selector passed. Just remember that the selector should follow the CSS syntax. In case you do not have any selector, it returns null.
它返回傳遞了特定CSS選擇器的第一個元素 。 請記住, 選擇器應遵循CSS語法 。 如果沒有任何選擇器 ,它將返回null 。
var resetButton = document.querySelector('#reset');
resetButton: Our variable name that looks similar to our selector passed.
resetButton :我們的變量名看起來與傳遞的選擇器相似。
#reset: selector passed, and if you don’t have any selector that matches it returns null.
#reset : 選擇器已傳遞,如果沒有與之匹配的選擇器 ,則返回null 。
querySelectorAll() (querySelectorAll())
Very similar to the querySelector() method, but with a single difference: it returns all the elements that match with the CSS selector passed. The selector should also follow the CSS syntax. In case you do not have any selector, it returns null.
與querySelector()方法非常相似,但有一個區別:它返回與傳遞的CSS選擇器匹配的所有元素 。 選擇器還應遵循CSS語法 。 如果沒有選擇器 ,則返回null 。
var myButtons = document.querySelector('#buttons');
myButtons: Our variable name that looks similar to our selectors passed.
myButtons :看起來與傳遞的選擇器相似的變量名。
#buttons: selector passed, if you don’t have any selector that matches it returns null.
#buttons :通過選擇器 ,如果沒有與之匹配的選擇器 ,則返回null 。
Those are some the most used DOM methods. There are several more methods that you can use, like the createElement(), which creates a new element in your HTML page, and setAttribute() that lets you set new attributes for elements HTML. You can explore them on your own.
這些是最常用的DOM方法。 還有其他幾種方法可以使用,例如createElement()在HTML頁面中創建一個新元素,以及setAttribute(),用于為HTML元素設置新屬性。 您可以自己探索它們。
Again, you can find all the methods here, on the left side in Methods. I really recommend you take a look at some of the others because you might need one of them sometime soon.
同樣,您可以在“方法”左側的此處找到所有方法 。 我真的建議您看看其他一些,因為您可能很快就會需要其中一些。
Now, we’re going to learn about Events — after all without them we can’t make animations in our pages.
現在,我們將學習事件 -畢竟,如果沒有事件 ,我們將無法在頁面中制作動畫。
大事記 (Events)
The DOM elements have methods, as we just discussed, but they also have events. These events are responsible for make interactivity possible in our page. But here’s one thing that you might not know: events are also methods.
就像我們剛剛討論的那樣,DOM元素具有方法 ,但是它們也具有事件 。 這些事件負責使我們頁面中的交互成為可能。 但是,您可能不知道這件事: 事件也是方法 。
點擊 (click)
One of the most used events is the click event. When the user clicks on a specific element, it will realize some action.
點擊事件是最常用的事件之一。 當用戶單擊特定元素時,它將實現一些操作。
myStart.addEventListener('click', function(event) {
// Do something here.
}, false);
The addEventListener() parameters are:
addEventListener()參數為:
The type of the event that you want (in this case ‘click’).
所需事件的類型(在這種情況下為“ 單擊 ”)。
- A callback function 回調函數
The useCapture by default is false. It indicates whether or not you want to “capture” the event.
默認情況下, useCapture為false。 它指示您是否要“捕獲”事件。
選擇 (select)
This events is for when you want to dispatch something when a specific element is selected. In that case we’re gonna dispatch a simple alert.
當選擇特定元素時要分派某些東西時,將使用此事件。 在這種情況下,我們將發出一個簡單的警報 。
myStart.addEventListener('select', function(event) {
alert('Element selected!');
}, false);
These are some of the most commonly used events. Of course, we have a lot of other events that you can use, like drag & drop events — when a user starts to drag some element you can make some action, and when they drop that element you can make another action.
這些是一些最常用的事件。 當然,我們還有許多其他事件可以使用,例如拖放事件-當用戶開始拖動某個元素時,您可以執行某些操作,而當用戶拖放該元素時,您可以執行另一個操作。
Now, we’re gonna see how we can traverse the DOM and use some properties.
現在,我們將看到如何遍歷DOM并使用一些屬性。
遍歷DOM (Traversing the DOM)
You can traverse the DOM and use some properties that we’re gonna see now. With these properties, you can return elements, comments, text, and so on.
您可以遍歷DOM并使用我們現在要看到的一些屬性。 使用這些屬性,您可以返回元素,注釋,文本等。
.childNodes (.childNodes)
This property returns a nodeList of child nodes of the given element. It returns text, comments, and so on. So, when you want to use it, you should be careful.
此屬性返回給定元素的子節點的nodeList 。 它返回文本,注釋等。 因此,當您要使用它時,應該小心。
var container = document.querySelector('.container');
var getContainerChilds = container.childNodes;
。第一個孩子 (.firstChild)
This property returns the first child of the given element.
此屬性返回給定元素的第一個孩子。
var container = document.querySelector('.container');
var getFirstChild = container.firstChild;
.nodeName (.nodeName)
This property returns the name of the given element. In this case, we passed a div, so it will return “div”.
此屬性返回給定元素的名稱。 在這種情況下,我們傳遞了一個div ,因此它將返回“ div ”。
var container = document.querySelector('.container');
var getName = container.nodeName;
.nodeValue (.nodeValue)
This property is specific for texts and comments, as it returns or sets the value of the current node. In this case, since we passed a div, it will return null.
此屬性特定于文本和注釋 ,因為它返回或設置當前節點的值。 在這種情況下,由于我們傳遞了div,因此它將返回null 。
var container = document.querySelector('.container')
var getValue = container.nodeValue;
.nodeType (.nodeType)
This property returns the type of the given element. In this case, it returns “1”.
此屬性返回給定元素的類型 。 在這種情況下,它返回“ 1 ”。
var container = document.querySelector('.container')
var getValue = container.nodeType;
But, what does “1” mean anyway? It is basically the nodeType of the given element. In this case, it is an _ELEMENT_NODE_ and returns null. If this were an attribute, it would be returned as “2” to us and the attribute value.
但是,“ 1 ”到底是什么意思? 它基本上是給定元素的nodeType 。 在這種情況下,它是_ELEMENT_NODE_并返回null。 如果這是一個屬性,它將以“ 2 ”的形式返回給我們和屬性值。
You can read more about nodeTypes here.
您可以在此處閱讀有關nodeTypes的更多信息。
元素 (Elements)
These properties, instead of those above, return to us only elements. They are more often used and recommended because they can cause less confusion and are easier to understand.
這些屬性(而不是上面的屬性)僅返回給我們elements 。 它們更經常使用和推薦,因為它們可以減少混亂并且更易于理解。
.parentNode (.parentNode)
This property returns the parent of the node given.
此屬性返回給定節點的父級。
var container = document.querySelector('.container')
var getParent = container.parentNode;
.firstElementChild (.firstElementChild)
Returns the first child element of the given element.
返回給定元素的第一個子元素。
var container = document.querySelector('.container')
var getValue = container.firstElementChild;
.lastElementChild (.lastElementChild)
Returns the last child element of the given element.
返回給定元素的最后一個子元素。
var container = document.querySelector('.container')
var getValue = container.lastElementChild;
These are some of the many properties that the DOM has. It’s very important for you to know the basics about the DOM, how it works, and its methods and properties, because some day you may need it.
這些是DOM具有的許多屬性中的一些。 了解DOM的基本知識,它的工作方式以及它的方法和屬性對您來說非常重要,因為有一天您可能會需要它。
結論 (Conclusion)
The DOM provides us with several important API's for creating fantastic and innovative applications. If you understand the basics of it you can create incredible things. If you want to read more about the DOM, you can click here and read all the MDN docs.
DOM為我們提供了幾個重要的API,可用于創建出色的創新應用程序。 如果您了解它的基礎知識,則可以創建令人難以置信的東西。 如果您想了解有關DOM的更多信息,可以單擊此處并閱讀所有MDN文檔。
? Follow me on Twitter! ? Follow me on GitHub!
? 在Twitter上關注我! ? 在GitHub上關注我!
I’m looking for a remote opportunity, so if have any I’d love to hear about it, so please contact me!
我正在尋找機會,所以如果有任何我想聽到的機會,請與我聯系!
翻譯自: https://www.freecodecamp.org/news/whats-the-document-object-model-and-why-you-should-know-how-to-use-it-1a2d0bc5429d/
文檔對象模型dom