文檔對象模型dom_什么是文檔對象模型,以及為什么應該知道如何使用它。

文檔對象模型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:

在上圖中,我們可以看到代表性樹以及瀏覽器如何創建它。 在此示例中,我們將看到四個重要的元素:

  1. Document: It treats all the HTML documents.

    Document :處理所有HTML文檔。

  2. Elements: All the tags that are inside your HTML or XML turn into a DOM element.

    元素HTMLXML內的所有標簽都將變成DOM元素。

  3. Text: All the tags’ content.

    文字 :所有標簽的內容。

  4. 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()參數為:

  1. The type of the event that you want (in this case ‘click’).

    所需事件的類型(在這種情況下為“ 單擊 ”)。

  2. A callback function

    回調函數
  3. 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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/393171.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/393171.shtml
英文地址,請注明出處:http://en.pswp.cn/news/393171.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

安裝Docker step by step

1. 系統要求 centos7以上 使用cat /etc/redhat-release查看系統版本&#xff0c;我的Centos 7.6 centos-extra 倉庫 enable&#xff0c;默認是打開的 2.安裝docker docer安裝分為聯網安裝和離線安裝兩種安裝 方式&#xff0c; 第一種 在有外網環境下安裝docker,一般使用yum安…

linux用戶空間和內核exit的語義--linux沒有線程

如果你在程序中調用了exit&#xff0c;那么很顯然你的程序會退出&#xff0c;可是至于為何會退出那就是庫的事情了&#xff0c;我為什么說只是庫的事情而不關linux內核的事情呢&#xff1f;那是因為linux內核根本不管用戶空間的行為策略。庫的策略是什么&#xff1f;很簡單的退…

leetcode1328. 破壞回文串

給你一個回文字符串 palindrome &#xff0c;請你將其中 一個 字符用任意小寫英文字母替換&#xff0c;使得結果字符串的字典序最小&#xff0c;且 不是 回文串。 請你返回結果字符串。如果無法做到&#xff0c;則返回一個空串。 示例 1&#xff1a; 輸入&#xff1a;palindro…

php補充 擴展,PHP安裝擴展補充說明

上一篇文章中用到了&#xff0c;php的sodium擴展&#xff0c;那么如何安裝PHP擴展呢&#xff1f;基于我之前踩過的一些坑&#xff0c;大致整理了幾種安裝php擴展的方法。已安裝sodium為例1、先做點準備工作&#xff0c;安裝sodium依賴rpm -ivh http://mirrors.whsir.com/centos…

Java調用存儲過程出現Bug,sql語法錯誤

因為SQL Server運行沒有正常,檢查了傳入參數的值,發現問題,然后傳入默認參數,解決了問題.轉載于:https://www.cnblogs.com/JimmySeraph/p/11043490.html

leetcode1438. 絕對差不超過限制的最長連續子數組

給你一個整數數組 nums &#xff0c;和一個表示限制的整數 limit&#xff0c;請你返回最長連續子數組的長度&#xff0c;該子數組中的任意兩個元素之間的絕對差必須小于或者等于 limit 。 如果不存在滿足條件的子數組&#xff0c;則返回 0 。 示例 1&#xff1a; 輸入&#…

gitlab 2.7版本升級到2.8

第一步 關閉服務 /etc/init.d/gitlab stop第二部 更新代碼cd /home/gitlab/gitlab# Get latest codesudo -u gitlab git pull origin stable# Install libssudo -u gitlab bundle install --without development test# update dbsudo -u gitlab bundle exec rake db:migrate RA…

arkit技術介紹_面向移動AR的觸覺技術:如何以“觸摸”感增強ARKit應用

arkit技術介紹by Neil Mathew通過尼爾馬修(Neil Mathew) 面向移動AR的觸覺技術&#xff1a;如何以“觸摸”感增強ARKit應用 (Haptics for mobile AR: how to enhance ARKit apps with a sense of “touch”) I’m really excited about the future of haptics for AR and VR. …

Unity3D的坑系列:動態加載dll

Unity3D的坑系列&#xff1a;動態加載dll 我現在參與的項目是做MMO手游&#xff0c;目標平臺是Android和iOS&#xff0c;iOS平臺不能動態加載dll&#xff08;什么原因找喬布斯去&#xff09;&#xff0c;可以直接忽略&#xff0c;而在Android平臺是可以動態加載dll的&#xff0…

微信小程序 php配置,微信小程序的配置

我們使用app.json文件來對微信小程序進行全局配置&#xff0c;決定頁面文件的路徑、窗口表現、設置網絡超時時間、設置多 tab 等。以下是一個包含了所有配置選項的簡單配置app.json{"pages": ["pages/index/index","pages/logs/index"],"wi…

leetcode332. 重新安排行程(dfs)

給定一個機票的字符串二維數組 [from, to]&#xff0c;子數組中的兩個成員分別表示飛機出發和降落的機場地點&#xff0c;對該行程進行重新規劃排序。所有這些機票都屬于一個從 JFK&#xff08;肯尼迪國際機場&#xff09;出發的先生&#xff0c;所以該行程必須從 JFK 開始。 …

PWA - service worker - Workbox(未完)

Get Started&#xff08;開始&#xff09; 只有get請求才能cache緩存嗎&#xff1f;Create and Register a Service Worker File&#xff08;創建和注冊 Service Worker&#xff09; Before we can use Workbox, we need to create a service worker file and register it to o…

draft.js_如何使用快捷方式在Draft.js中創建有序列表和無序列表

draft.jsby Andrey Semin通過安德烈塞米(Andrey Semin) 如何使用快捷方式在Draft.js中創建有序列表和無序列表 (How to create ordered and unordered lists in Draft.js with a shortcut) We at Propeller have encountered many differences between Draft.js and popular t…

當javaScript從入門到提高前需要注意的細節:變量部分

到了HTML5的時代&#xff0c;對javaScript的要求不是降低了&#xff0c;而是更提高了。javaScript語言的入門非常簡單&#xff0c;如果你有java、C#等C風格的結構化語言的基礎&#xff0c;那javaScript你最多半天就可以寫點什么了。但是javaScript是一種動態語言&#xff0c;這…

PAT乙級 1003. 我要通過!

題目&#xff1a; “答案正確”是自動判題系統給出的最令人歡喜的回復。本題屬于PAT的“答案正確”大派送 —— 只要讀入的字符串滿足下列條件&#xff0c;系統就輸出“答案正確”&#xff0c;否則輸出“答案錯誤”。 得到“答案正確”的條件是&#xff1a; 1. 字符串中必須僅有…

電臺復活節_如何通過在控制臺中隱藏復活節彩蛋使您的應用程序用戶驚訝

電臺復活節by Ethan Ryan由伊桑瑞安(Ethan Ryan) 如何通過在控制臺中隱藏復活節彩蛋使您的應用程序用戶驚訝 (How to surprise your app’s users by hiding Easter eggs in the console) I love console.logging(“stuff”).我喜歡console.logging(“ stuff”)。 I do it th…

leetcode1267. 統計參與通信的服務器(dfs)

這里有一幅服務器分布圖&#xff0c;服務器的位置標識在 m * n 的整數矩陣網格 grid 中&#xff0c;1 表示單元格上有服務器&#xff0c;0 表示沒有。 如果兩臺服務器位于同一行或者同一列&#xff0c;我們就認為它們之間可以進行通信。 請你統計并返回能夠與至少一臺其他服務…

System類入門學習

第三階段 JAVA常見對象的學習 System類 System類包含一些有用的字段和方法&#xff0c;他不能被實例化 //用于垃圾回收 public static void gc()//終止正在運行的java虛擬機。參數用作狀態碼&#xff0c;根據慣例&#xff0c;非0表示異常終止 public static void exit(int stat…

gulpfile php,Laravel利用gulp如何構建前端資源詳解

什么是gulp&#xff1f;gulp是新一代的前端項目構建工具&#xff0c;你可以使用gulp及其插件對你的項目代碼(less,sass)進行編譯&#xff0c;還可以壓縮你的js和css代碼&#xff0c;甚至壓縮你的圖片&#xff0c;gulp僅有少量的API&#xff0c;所以非常容易學習。 gulp 使用 st…

ios jenkins_如何使用Jenkins和Fastlane制作iOS點播構建系統

ios jenkinsby Agam Mahajan通過Agam Mahajan 如何使用Jenkins和Fastlane制作iOS點播構建系統 (How to make an iOS on-demand build system with Jenkins and Fastlane) This article is about creating iOS builds through Jenkins BOT, remotely, without the need of a de…