vanilla_如何在Vanilla JavaScript中操作DOM

vanilla

by carlos da costa

通過卡洛斯·達·科斯塔

如何在Vanilla JavaScript中操作DOM (How to manipulate the DOM in Vanilla JavaScript)

So you have learned variables, selection structures, and loops. Now it is time to learn about DOM manipulation and to start doing some cool JavaScript projects.

因此,您已經了解了變量,選擇結構和循環。 現在是時候學習DOM操作并開始做一些很棒JavaScript項目了。

In this tutorial, we will learn how to manipulate the DOM with vanilla JavaScript. With no further ado, let’s jump right into it.

在本教程中,我們將學習如何使用原始JavaScript操作DOM。 事不宜遲,讓我們直接進入。

1.首先 (1. First things first)

Before we dive into coding, let’s learn what the Dom really is:

在開始編碼之前,讓我們學習一下Dom的真正含義:

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page. Source

文檔對象模型(DOM)是HTML和XML文檔的編程接口。 它代表頁面,以便程序可以更改文檔的結構,樣式和內容。 DOM將文檔表示為節點和對象。 這樣,編程語言可以連接到頁面。 資源

Basically, when a browser loads a page it creates an object model of that page and prints it on the screen. The object model is represented in a tree data structure, each node is an object with properties and methods, and the topmost node is the document object.

基本上,瀏覽器在加載頁面時會創建該頁面的對象模型并將其打印在屏幕上。 對象模型以樹形數據結構表示,每個節點是具有屬性和方法的對象,而最頂層的節點是文檔對象。

A programming language can be used to access and modify this object model, and this action is called DOM manipulation. And we will do that with JavaScript because JS is awesome.

可以使用一種編程語言來訪問和修改此對象模型,此操作稱為DOM操作。 我們將使用JavaScript來實現,因為JS非常棒。

2.實際教程 (2. The actual tutorial)

For the tutorial, we are going to need two files, one index.html, and the other manipulation.js.

對于本教程,我們將需要兩個文件,一個為index.html,另一個為control.js。

<!-- Index.html file --><html>  <head>    <title>DOM Manipulation</title>  </head>  <body>     <div id="division"><h1 id="head"><em>DOM<em> manipulation</h1>      <p class="text" id="middle">Tutorial</p><p>Sibling</p>      <p class="text">Medium Tutorial</p>    </div>    <p class="text">Out of the div</p>    <!-- Then we call the javascript file -->    <script src="manipulation.js"></script>  </body></html>

So there we have our HTML file, and as you can see we have a div with the id of division. Inside of that we have an h1 element, and in the same line, you will understand why later, we have two p elements and the div closing tag. Finally we have a p element with a class of text.

這樣我們就有了HTML文件,并且您可以看到我們有一個帶除法ID的div。 在其中,我們有一個h1元素,并且在同一行中,您將了解為什么以后有兩個p元素和div結束標記。 最后,我們有帶有一類文本的ap元素。

2.1。 訪問元素 (2.1. Accessing the elements)

We can either access a single element or multiple elements.

我們可以訪問單個元素或多個元素。

2.1.1。 訪問單個元素 (2.1.1. Accessing a single element)

For accessing a single element, we will look at two methods: getElementByID and querySelector.

為了訪問單個元素,我們將看兩種方法:getElementByID和querySelector。

// the method below selects the element with the id ofheadlet id = document.getElementById('head');
// the code below selects the first p element inside the first divlet q = document.querySelector('div p');
/* Extra code */// this changes the color to redid.style.color = 'red';// give a font size of 30pxq.style.fontSize = '30px';

Now we have accessed two elements, the h1 element with the id of head and the first p element inside the div.

現在,我們訪問了兩個元素,具有id為head的h1元素和div中的第一個p元素。

getElementById takes as argument an id, and querySelector takes as argument a CSS selector and returns the first element that matches the selector. As you can see I assigned the methods outcome into variables, and then I added some styling at the end.

getElementById將id作為參數, querySelector將CSS選擇器作為參數,并返回與選擇器匹配的第一個元素。 如您所見,我將方法的結果分配給變量,然后在最后添加一些樣式。

2.1.2。 訪問多個元素 (2.1.2. Accessing multiple elements)

When accessing multiple elements, a node list is returned. It is not an array but it works like one. So you can loop through it and use the length property to get the size of the node list. If you want to get a specific element you can either use the array notation or the item method. You will see them in the code.

當訪問多個元素時,將返回一個節點列表。 它不是數組,但是像一個數組。 因此,您可以遍歷它,并使用length屬性來獲取節點列表的大小。 如果要獲取特定元素,則可以使用數組符號或item方法。 您將在代碼中看到它們。

For accessing multiple elements we are going to use three methods: getElementsByClassName, getElementsByTagName, and querySelectorAll.

為了訪問多個元素,我們將使用三種方法:getElementsByClassName,getElementsByTagName和querySelectorAll。

// gets every element with the class of textlet className = document.getElementsByClassName('text');
// prints the node listconsole.log(className);
/* prints the third element from the node list using array notation */console.log(className[2]);
/* prints the third element from the node list using the item function */console.log(className.item(2));
let tagName = document.getElementsByTagName('p');let selector = document.querySelectorAll('div p');

The code seems to be self-explanatory, but I will explain it anyway because I am a nice dude. :)

該代碼似乎是不言自明的,但是我還是會解釋它,因為我是一個好人。 :)

First, we use the getElementsByClassName that takes a class name as an argument. It returns a node list with every element that has text as a class. Then we print the node list on the console. We also print the third element from the list using the array notation and the item method.

首先,我們使用以類名作為參數的getElementsByClassName 。 它返回一個節點列表,其中每個元素都有以文本為類的元素。 然后我們在控制臺上打印節點列表。 我們還使用數組符號item方法從列表中打印第三個元素。

Second, we select every p element using the getElementsByTagName method that takes a tag name as an argument and returns a node list of that element.

其次,我們使用getElementsByTagName方法選擇每個p元素,該方法將標簽名稱作為參數并返回該元素的節點列表。

Finally, we use the querySelectorAll method, that takes as an argument a CSS selector. In this case, it takes div p so it will return a node list of p elements inside a div.

最后,我們使用querySelectorAll方法,該方法將CSS選擇器作為參數。 在這種情況下,它需要div p,因此它將返回div中p個元素的節點列表。

As a practice exercise, print all the elements from tagName and selector node list and find out their size.

作為練習,打印來自tagName選擇器節點列表的所有元素,并找出它們的大小。

2.2。 遍歷DOM (2.2. Traversing the DOM)

So far we have found a way of accessing specific elements. What if we want to access an element next to an element that we have already accessed, or access the parent node of a previously accessed element? The properties firstChild, lastChild, parentNode, nextSibling, and previousSibling can get this job done for us.

到目前為止,我們已經找到了訪問特定元素的方法。 如果我們要訪問已經訪問過的元素旁邊的元素,或者訪問以前訪問過的元素的父節點,該怎么辦? 屬性firstChild,lastChild,parentNode,nextSiblingpreviousSibling可以為我們完成這項工作。

firstChild is used to get the first child element of a node. lastChild, as you guessed, it gets the last child element of a node. parentNode is used to access a parent node of an element. nextSibling gets for us the element next to the element already accessed, and previousSibling gets for us the element previous to the element already accessed.

firstChild用于獲取節點的第一個子元素。 如您所猜, lastChild ,它獲取節點的最后一個子元素。 parentNode 用于訪問元素的父節點。 nextSibling為我們獲取已訪問元素旁邊的元素,而previousSibling為我們獲取已訪問元素之前的元素。

// gets first child of the element with the id of divisionlet fChild = document.getElementById('division').firstChild;console.log(fChild);
// gets the last element from element with the id of divisionlet lChild = document.querySelector('#division').lastChild;
// gets the parent node of the element with the id divisionlet parent = document.querySElector('#division').parentNode;console.log(parent);
// selects the element with the id of middlelet middle = document.getElementById('middle');// prints ond the console the next sibling of middleconsole.log(middle.nextSibling);

The code above first gets the firstChild element of the element with the division id and then prints it on the console. Then it gets the lastChild element from the same element with the division id. Then it gets the parentNode of the element with the id of division and prints it on the console. Finally, it selects the element with the id of middle and prints its nextSibling node.

上面的代碼首先獲取具有分區ID的元素的firstChild元素,然后將其打印在控制臺上。 然后,它從具有除法ID的同一元素中獲取lastChild元素。 然后,它獲取具有除法ID的元素的parentNode并將其打印在控制臺上。 最后,它選擇id為middle的元素并打印其nextSibling節點。

Most browsers treat white spaces between elements as text nodes, which makes these properties work differently in different browsers.

大多數瀏覽器將元素之間的空白視為文本節點,這使得這些屬性在不同的瀏覽器中的工作方式有所不同。

2.3。 獲取和更新元素內容 (2.3. Get and Updating element content)

2.3.1. Setting and getting text Content

2.3.1。 設置和獲取文字內容

We can get or set the text content of elements. To achieve this task we are going to use two properties: nodeValue and textContent.

我們可以獲取或設置元素的文本內容。 為了完成此任務,我們將使用兩個屬性: nodeValuetextContent

nodeValue is used to set or get the text content of a text node. textContent is used to set or get the text of a containing element.

nodeValue用于設置或獲取文本節點的文本內容。 textContent用于設置或獲取包含元素的文本。

// get text with nodeValuelet nodeValue = document.getElementById('middle').firstChild.nodeValue;console.log(nodeValue);
// set text with nodeValuedocument.getElementById('middle').firstChild.nodeValue = "nodeValue text";
// get text with textContentlet textContent = document.querySelectorAll('.text')[1].textContent;console.log(textContent);
// set text with textContentdocument.querySelectorAll('.text')[1].textContent = 'new textContent set';

Did you notice the difference between nodeValue and textContent?

您是否注意到nodeValuetextContent之間的區別?

If you look carefully at the code above, you will see that for us to get or set the text with nodeValue, we first had to select the text node. First, we got the element with the middle id, then we got its firstChild which is the text node, then we got the nodeValue which returned the word Tutorial.

如果仔細看一下上面的代碼,您將看到,要讓我們使用nodeValue獲取或設置文本,我們首先必須選擇文本節點。 首先,我們獲得具有中間 ID的元素,然后獲得其firstChild (即文本節點),然后獲得nodeValue并返回單詞Tutorial。

Now with textContent, there is no need to select the text node, we just got the element and then we got its textContent, either to set and get the text.

現在有了textContent ,就無需選擇文本節點,我們只需獲取元素,然后獲取其textContent即可設置和獲取文本。

2.3.2. Adding and Removing HTML content

2.3.2。 添加和刪??除HTML內容

You can add and remove HTML content in the DOM. For that, we are going to look at three methods and one property.

您可以在DOM中添加和刪除HTML內容。 為此,我們將研究三種方法和一種屬性。

Let’s start with the innerHTML property because it is the easiest way of adding and removing HTML content. innerHTML can either be used to get or set HTML content. But be careful when using innerHTML to set HTML content, because it removes the HTML content that is inside the element and adds the new one.

讓我們從innerHTML屬性開始,因為它是添加和刪除HTML內容的最簡單方法。 innerHTML可以用于獲取或設置HTML內容。 但是在使用innerHTML設置HTML內容時要小心,因為它會刪除元素內HTML內容并添加新元素。

document.getElementById('division').innerHTML =`<ul>  <li>Angular</li>  <li>Vue</li>  <li>React</li></ul>`;

If you run the code, you will notice that everything else in the div with the id of division will disappear, and the list will be added.

如果運行代碼,您會注意到div中ID為divid的所有其他內容都將消失,并將添加列表。

We can use the methods: createElement(), createTextNode(), and appendChild() to solve this problem.

我們可以使用以下方法: createElement() ,c reateTextNode()appendChild()解決此問題。

createElement is used to create a new HTML element. creatTextNode used to create a text node, and appendChild is used to append a new element into a parent element.

createElement用于創建新HTML元素。 creatTextNode用于創建文本節點,appendChild用于將新元素附加到父元素中。

//first we create a new p element using the creatElementlet newElement = document.createElement('p');/* then we create a new text node and append the text node to the element created*/let text = document.createTextNode('Text Added!');newElement.appendChild(text);
/* then we append the new element with the text node into the div with the id division.*/document.getElementById('division').appendChild(newElement);

There is also a method called removeChild used to remove HTML elements.

還有一個稱為removeChild的方法,用于刪除HTML元素。

// first we get the element we want to removelet toBeRemoved = document.getElementById('head');// then we get the parent node, using the parentNOde propertylet parent = toBeRemoved.parentNode;/* then we use the removeChild method, with the element to be removed as a parameter.*/parent.removeChild(toBeRemoved);

So first we get the element that we want to remove, and then we get its parent node. Then we called the method removeChild to remove the element.

因此,首先獲得要刪除的元素,然后獲得其父節點。 然后我們調用方法removeChild刪除元素。

2.4。 屬性節點 (2.4. Attribute node)

Now we know how to handle elements, so let’s learn how to handle the attributes of these elements. There are some methods like GetAttribute, setAttribute, hasAttribute, removeAttribute, and some properties like className and id.

現在我們知道了如何處理元素,因此讓我們學習如何處理這些元素的屬性。 有一些方法,例如GetAttributesetAttributehasAttributeremoveAttribute和一些屬性,例如classNameid

getAttribute as its name may suggest, it is used to get an attribute. Like the class name, the id name, the href of a link or any other HTML attribute.

顧名思義, getAttribute用來獲取屬性。 像類名,ID名稱,鏈接的href或任何其他HTML屬性一樣。

setAttribute is used to set a new attribute to an element. It takes two arguments, first the attribute and second the name of the attribute.

setAttribute用于為元素設置新屬性。 它帶有兩個參數,第一個是屬性,第二個是屬性名稱。

hasAttribute used to check if an attribute exists, takes an attribute as an argument.

hasAttribute用于檢查屬性是否存在,將屬性作為參數。

removeAttribute used to remove an attribute, it takes an attribute as an argument.

removeAttribute用于刪除屬性,它接受屬性作為參數。

Id this property is used to set or get the id of an element.

id此屬性用于設置或獲取元素的id。

ClassName is used to set or get the class of an element.

ClassName用于設置或獲取元素的類。

// selects the first divlet d = document.querySelector('div');// checks if it has an id attribute, returns true/falseconsole.log('checks id: '+d.hasAttribute('id'));// set a new class attributed.setAttribute('class','newClass');// returns the class nameconsole.log(d.className);

I know I am a good dude, but that code is just self-explanatory.

我知道我是一個好家伙,但是該代碼是不言自明的。

結論 (Conclusion)

That is it! We have learned so many concepts, but there is more to learn about DOM manipulation. What we have covered here gives you a good foundation.

這就對了! 我們已經學習了很多概念,但是還有更多關于DOM操作的知識。 我們在這里介紹的內容為您奠定了良好的基礎。

Go ahead and practice, and create something new to cement this new knowledge.

繼續練習,并創建一些新東西來鞏固這一新知識。

Good day, good coding.

美好的一天,良好的編碼。

翻譯自: https://www.freecodecamp.org/news/dom-manipulation-in-vanilla-js-2036a568dcd9/

vanilla

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

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

相關文章

NOIP201202尋寶

題目 試題描述傳說很遙遠的藏寶樓頂層藏著誘人的寶藏。 小明歷盡千辛萬苦終于找到傳說中的這個藏寶樓&#xff0c;藏寶樓的門口豎著一個木板&#xff0c;上面寫有幾個大字&#xff1a;尋寶說明書。說明書的內容如下&#xff1a;藏寶樓共有N1層&#xff0c;最上面一層是頂層&…

修改UITextField中的placeholder的字體

修改字體顏色&#xff1a; [textField setValue:[UIColor redColor] forKeyPath:"_placeholderLabel.textColor"]; 復制代碼 修改字體大小&#xff1a; [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:"_placeholderLabel.font"]; 復…

如何使用Python處理丟失的數據

The complete notebook and required datasets can be found in the git repo here完整的筆記本和所需的數據集可以在git repo中找到 Real-world data often has missing values.實際數據通常缺少值 。 Data can have missing values for a number of reasons such as observ…

MySQL—隔離級別

READ UNCOMMITED(讀未提交) 即讀取到了正在修改但是卻還沒有提交的數據&#xff0c;這就會造成數據讀取的錯誤。 READ COMMITED(提交讀/不可重復讀) 它與READ UNCOMMITED的區別在于&#xff0c;它規定讀取的時候讀到的數據只能是提交后的數據。 這個級別所帶來的問題就是不可…

做虛擬化服務器的配資一致嘛,服務器虛擬化技術在校園網管理中的應用探討.pdf...

第 卷 第 期 江 蘇 建 筑 職 業 技 術 學 院 學 報14 3 Vol.14 曧.3年 月 JOURNAL OF JIANGSU JIANZHU INSTITUTE2014 09 Se .2014p服務器虛擬化技術在校園網管理中的應用探討,汪小霞 江建( , )健雄職業技術學院 軟件與服務外包學院 江蘇 太倉 215411: , ,摘 要 高校校園網數據…

aws中部署防火墻_如何在AWS中設置自動部署

aws中部署防火墻by Harry Sauers哈里紹爾斯(Harry Sauers) 如何在AWS中設置自動部署 (How to set up automated deployment in AWS) 設置和配置服務器 (Provisioning and Configuring Servers) 介紹 (Introduction) In this tutorial, you’ll learn how to use Amazon’s AWS…

Runtime的應用

來自&#xff1a;http://www.imlifengfeng.com/blog/?p397 1、快速歸檔 (id)initWithCoder:(NSCoder *)aDecoder { if (self [super init]) { unsigned int outCount; Ivar * ivars class_copyIvarList([self class], &outCount); for (int i 0; i < outCount; i ) …

使用 VisualVM 進行性能分析及調優

https://www.ibm.com/developerworks/cn/java/j-lo-visualvm/轉載于:https://www.cnblogs.com/adolfmc/p/7238893.html

spring—事務控制

編程式事務控制相關對象 PlatformTransactionManager PlatformTransactionManager 接口是 spring 的事務管理器&#xff0c;它里面提供了我們常用的操作事務的方法。注意&#xff1a; PlatformTransactionManager 是接口類型&#xff0c;不同的 Dao 層技術則有不同的實現類 …

為什么印度盛產碼農_印度農產品價格的時間序列分析

為什么印度盛產碼農Agriculture is at the center of Indian economy and any major change in the sector leads to a multiplier effect on the entire economy. With around 17% contribution to the Gross Domestic Product (GDP), it provides employment to more than 50…

SAP NetWeaver

SAP的新一代企業級服務架構——NetWeaver    SAP NetWeaver是下一代基于服務的平臺&#xff0c;它將作為未來所有SAP應用程序的基礎。NetWeaver包含了一個門戶框架&#xff0c;商業智能和報表&#xff0c;商業流程管理&#xff08;BPM&#xff09;&#xff0c;自主數據管理&a…

NotifyMyFrontEnd 函數背后的數據緩沖區(一)

async.c的 static void NotifyMyFrontEnd(const char *channel, const char *payload, int32 srcPid) 函數中的主要邏輯是這樣的&#xff1a;復制代碼if (whereToSendOutput DestRemote) { StringInfoData buf; pq_beginmessage(&buf, A); //cursor 為 A pq…

最后期限 軟件工程_如何在軟件開發的最后期限內實現和平

最后期限 軟件工程D E A D L I N E…最后期限… As a developer, this is one of your biggest nightmares or should I say your enemy? Name it whatever you want.作為開發人員&#xff0c;這是您最大的噩夢之一&#xff0c;還是我應該說您的敵人&#xff1f; 隨便命名。 …

SQL Server的復合索引學習【轉載】

概要什么是單一索引,什么又是復合索引呢? 何時新建復合索引&#xff0c;復合索引又需要注意些什么呢&#xff1f;本篇文章主要是對網上一些討論的總結。一.概念單一索引是指索引列為一列的情況,即新建索引的語句只實施在一列上。用戶可以在多個列上建立索引&#xff0c;這種索…

leetcode 1423. 可獲得的最大點數(滑動窗口)

幾張卡牌 排成一行&#xff0c;每張卡牌都有一個對應的點數。點數由整數數組 cardPoints 給出。 每次行動&#xff0c;你可以從行的開頭或者末尾拿一張卡牌&#xff0c;最終你必須正好拿 k 張卡牌。 你的點數就是你拿到手中的所有卡牌的點數之和。 給你一個整數數組 cardPoi…

pandas處理excel文件和csv文件

一、csv文件 csv以純文本形式存儲表格數據 pd.read_csv(文件名)&#xff0c;可添加參數enginepython,encodinggbk 一般來說&#xff0c;windows系統的默認編碼為gbk&#xff0c;可在cmd窗口通過chcp查看活動頁代碼&#xff0c;936即代表gb2312。 例如我的電腦默認編碼時gb2312&…

tukey檢測_回到數據分析的未來:Tukey真空度的整潔實現

tukey檢測One of John Tukey’s landmark papers, “The Future of Data Analysis”, contains a set of analytical techniques that have gone largely unnoticed, as if they’re hiding in plain sight.John Tukey的標志性論文之一&#xff0c;“ 數據分析的未來 ”&#x…

spring— Spring與Web環境集成

ApplicationContext應用上下文獲取方式 應用上下文對象是通過new ClasspathXmlApplicationContext(spring配置文件) 方式獲取的&#xff0c;但是每次從容器中獲 得Bean時都要編寫new ClasspathXmlApplicationContext(spring配置文件) &#xff0c;這樣的弊端是配置文件加載多次…

Elasticsearch集群知識筆記

Elasticsearch集群知識筆記 Elasticsearch內部提供了一個rest接口用于查看集群內部的健康狀況&#xff1a; curl -XGET http://localhost:9200/_cluster/healthresponse結果&#xff1a; {"cluster_name": "format-es","status": "green&qu…

Item 14 In public classes, use accessor methods, not public fields

在public類中使用訪問方法&#xff0c;而非公有域 這標題看起來真晦澀。。解釋一下就是&#xff0c;如果類變成public的了--->那就使用getter和setter&#xff0c;不要用public成員。 要注意它的前提&#xff0c;如果是private的class&#xff08;內部類..&#xff09;或者p…