Javascript 简明教程

JavaScript - DOM Elements

The DOM Elements

HTML DOM elements 是文档对象模型元素的首字母缩写。借助 JavaScript,我们可以操作 HTM 元素。我们可以通过 id、属性、标记名称、类名称等访问 HTML 元素。

The HTML DOM elements is the acronym for the Document Object Model elements. With JavaScript, we can manipulate the HTM elements. We can access the HTML elements using id, attribute, tag name, class name, etc.

当网页在浏览器中加载时,它会创建一个 DOM tree 来代表网页的结构。网页包含各个 HTML elements ,您可以通过 JavaScript 中的属性和方法来操作它们。此处我们讨论如何访问、修改、替换等 DOM 元素。

When a web page loads in the browser, it creates a DOM tree representing the web page’s structure. The web page contains various HTML elements, which you can manipulate using the properties and methods in JavaScript. Here we will discuss to access, modify, or replace, etc. DOM elements.

Accessing DOM elements

您可以使用不同方法来访问 HTML 元素,如下所示。

You can use different methods to access HTML elements, as given below.

Get HTML Element using its "id"

在网页中,每个 HTML 元素都可以有一个唯一的 id 值。您可以使用 getElementById() 方法来访问 HTML 元素,方法是使用 id。

In the web page, each HTML element can have a unique id value. You can use the getElementById() method to access the HTML element using the id.

按照以下语法使用 getElemenetById() 方法来访问 HTML 元素,方法是使用它的 id。

Follow the syntax below to use the getElemenetById() method to access the HTML element using its id.

document.getElementById('id')

在以上语法中,您需要用元素的实际 id 替换“id”。

In the above syntax, you need to replace the 'id' with the actual id of the element.

在下面的代码中,我们使用 id 访问 div 元素,并使用 'innerHTML' 属性来改变它的内部 HTML。

In the below code, we access the div element using id and change its inner HTML using the 'innerHTML' property.

<html>
<body>
   <div id = "output"> </div>
   <script>
      document.getElementById('output').innerHTML =
		"The element is accessed using the id.";
   </script>
</body>
</html>
The element is accessed using the id.

Get an HTML element using the "name"

HTML 可以有一个“name”属性。您可以使用 getElementByName() 方法来访问 HTML 元素,方法是使用“name”属性的值。

An HTML can have a 'name' attribute. You can use the getElementByName() method to access the HTML element using the 'name' attribute’s value.

按照以下语法使用 getElementByName() 方法。

Follow the syntax below to use the getElementByName() method.

document.getElementsByName('name')

在此处,您需要用元素的 name 属性的值替换“name”。

Here, you need to replace the 'name' with a value of the element’s name attribute.

在下面的代码中,我们使用 name 访问 div 元素。它返回包含节点的数组,而节点作为参数传递。

In the below code, we access the div element using the name. It returns the array of nodes with the name passed as an argument.

<html>
<body>
   <div name = "text"> Hello World! </div>
   <div id = "output">The content of the div elment is:  </div>
   <script>
      const divEle = document.getElementsByName('text');
      document.getElementById("output").innerHTML += divEle[0].innerHTML;
   </script>
</body>
</html>
Hello World!
The content of the div elment is: Hello World!

Get HTML element using the "className"

HTML 的 class 属性包含字符串值。一个 HTML 元素也可以有多个类。您可以使用 getElementByClassName() 方法来访问 HTML 元素,方法是使用多个类名中的任意单个类名。

The class attribute of the HTML contains the string value. A single HTML element can also have multiple classes. You can use the getElementByClassName() method to access the HTML element using any single class name among multiples.

按照以下语法使用 getElementByClassName() 方法。

Follow the syntax below to use the getElementByClassName() method.

document.getElementsByClassName('className');

在以上语法中,用元素“class”属性的值替换“className”。

In the above syntax, replace the 'className' with the value of the elment’s 'class' attribute.

在下面的代码中,我们使用类名称访问 div 元素。

In the below code, we access the div element using the class name.

<html>
<body>
   <div class = "fruit"> Apple </div>
   <div id = "output">The name of the fruit is: </div>
   <script>
      const divEle = document.getElementsByClassName('fruit');
      document.getElementById("output").innerHTML += divEle[0].innerHTML;
   </script>
</body>
</html>
Apple
The name of the fruit is: Apple

Get an HTML element using the "tag" name

每个 HTML 元素都使用 HTML 标签定义。可以使用该标签的 getElementByTagName() 方法来使用标签名称访问 HTML 元素。

Each HTML element is defined using the HTML tag. You can use the tag getElementByTagName() method to access the HTML elements using the tag name.

使用 getElementByTagName() 方法时,请遵循以下语法。

Follow the syntax below to use the getElementByTagName() method.

document.getElementsByTagName('tag');

在上面的语法中,使用“p”、“a”、“img”等替换 HTML 标签中的“tag”。

In the above syntax, replace the 'tag' with the HTML tag like 'p', 'a', 'img', etc.

在下面的代码中,我们使用 getElementTagName() 方法访问 <p> 元素。

In the below code, we access the <p> elements using the getElementTagName() method.

它返回 <p> 元素的 Nodelist。

It returns the Nodelist of <p> elements.

<html>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragrraph.</p>
<div id = "output"> </div>
<script>
   const numbers = document.getElementsByTagName('p');
   document.getElementById("output").innerHTML =
   "The first 'p' element is: " + numbers[0].innerHTML + "<br>" +
   "The second 'p' element is: " + numbers[1].innerHTML;
</script>
</body>
</html>
This is the first paragraph.

This is the second paragrraph.

The first 'p' element is: This is the first paragraph.
The second 'p' element is: This is the second paragrraph.

Modifying the DOM Elements

JavaScript 允许修改和替换 HTML DOM 元素。

JavaScript allows you to modify and replace the HTML DOM elements.

在本节中,我们将介绍修改 DOM 元素的内容和替换子元素。

In this section, we will cover modifying DOM elements' content and replacing child elements.

Modify the Content of the DOM Element

可以使用元素的“textContent”属性来修改 HTML 元素的文本。但是,可以使用其他属性(如 innerHTML、outerHTML、outerText 等)来修改 HTML 元素的内容。

You can use the 'textContent' property of the element to modify the text of the HTML element. However, you can use other properties like innerHTML, outerHTML, outerText, etc., to modify the HTML element’s content.

遵循以下语法使用 textContent 属性修改 HTML 元素的文本内容。

Follow the syntax below to use the textContent property to modify the text content of the HTML element.

element.textContent = newText;

在上面的语法中,我们已将“newText”动态值分配给“textContent”属性以更新“element”的内容。

In the above syntax, we have assigned the 'newText' dynamic value to the 'textContent' property to update the content of the 'element'.

在输出中,单击按钮时将调用 updateText() 函数并使用 textContent 属性更改 div 元素的文本。

In the output, when you click the button, it will invoke the updateText() function and uses the textContent property to change the text of the div element.

<html>
<body>
   <button onclick = "updateText()"> Update Text </button>
   <p id = "text"> Hello World! </p>
   <script>
      function updateText() {
         document.getElementById("text").textContent = "This is updaetd text!";
      }
   </script>
</body>
</html>

Replace the Child Element

在 JavaScript 中,可以使用 replaceChild() 方法替换特定 HTML 元素的子元素。

In JavaScript, you can use the replaceChild() method to replace the child element of the particular HTML element.

按照以下语法在 JavaScript 中使用 replaceChild() 方法。

Follow the syntax below to use the replaceChild() method in JavaScript.

textDiv.replaceChild(newNode,replacableNode);

replaceChild() 方法将新的节点作为第一个参数,将需要替换的节点作为第二个参数。

The replaceChild() method takes a new node as a first parameter and a node that needs to be replaced as a second parameter.

在下面的代码中,我们使用 replaceChild() 方法将 div 元素的第二个子元素替换为一个新的节点。在这里,我们还使用了 createTextNode() 用“Hello World!”创建一个新的节点文本。

In the below code, we used the replaceChild() method to replace the second child of the div element with a new node. Here, we have also used the createTextNode() to create a new node with a 'Hello World!' text.

<html>
<body>
   <button onclick = "replaceText()"> Replace Child </button>
   <div id = "text">
      <p> Hi Users! </p>
   </div>
   <script>
      function replaceText() {
         let textDiv = document.getElementById("text");
         let newText = document.createTextNode("Hello World");
         textDiv.replaceChild(newText, textDiv.childNodes[1]);
      }
   </script>
</body>
</html>

Adding Events to the DOM Elements

可以使用 addEventListner() 方法向 DOM 元素添加事件以与 HTML 元素交互。

You can use addEventListner() method to add events to the DOM elements to interact with the HTML elements.

Syntax

使用 addEventListner() 方法时,请遵循以下语法。

Follow the syntax below to use the addEventListner() method.

element.addEventListener(eventName, callback);

addEventListner() 方法将事件名称作为第一个参数,回调函数作为第二个参数。

The addEventListner() method takes an event name as the first parameter and a callback function as a second parameter.

Example

我们在下面的代码中为 div 元素添加了 click 事件。每当单击它时,div 元素将在网页上打印一条消息。

We added the click event on the div element in the code below. The div element will print a message on the web page whenever you click it.

<html>
<body>
   <div id = "text" style = "background-color: red;color:white">
      <p> Some text </p>
      <p> Some other text </p>
   </div>
   <div id = "output"> </div>
   <script>
      let text = document.getElementById("text");
      text.addEventListener("click", function () {
         document.getElementById("output").innerHTML =
			"You clicked on the div element";
      });
   </script>
</body>
</html>

List of DOM Element Properties

下表包含您可以在 JavaScript 中与 HTML 元素结合使用的属性。

The table below contains the properties you can use with HTML elements in JavaScript.

Property

Description

accessKey

It is used to access or set the accessKey attribute of an HTML element.

attributes

It returns all attributes of the element in the NamedNodeMap format.

childElementCount

It returns the total number of children of the particular HTML element.

childNodes

It is used to get the NodeList of the child nodes of a particular HTML element.

children

It is used to get the HTML collection of child nodes of the HTML element.

classList

It returns the array containing the class names of the HTML element.

className

To get or set the value of the class attribute.

clientHeight

To get the height of the HTML element. (It includes the padding)

clientLeft

To get the width of the left border.

clientTop

To get the width of the right border.

clientWidth

To get the width of the HTML element. (It includes the padding)

contentEditable

To set the boolean value, representing whether the content of the HTML element should be editable.

dir

To set or get the direction of the text as ltr (left to right) or rtl (right to left).

firstChild

To get the first child node of the element.

firstElementChild

To get the first child element of the particular HTML element.

id

To get or set the value of the 'id' attribute.

innerHTML

To get or update the HTML of the element.

innerText

To set or get the text content of the HTML element and its children.

isContentEditable

It returns a Boolean value based on whether the content is editable.

isDefaultNamespace()

It returns a boolean value based on the namespace URI, which is the same as default.

lang

To set or get the value of the lang attribute.

lastChild

To get the last child node of the HTML element.

lastElementChild

To get the last child of the HTML element.

namespaceURI

To get the namespaceURI of the tree.

nextSibling

To get the next node at the same level in the DOM tree.

nextElementSibling

To get the next HTML element at the same level in the DOM tree.

nodeName

To get the name of the node.

nodeType

To get the type of the node.

nodeValue

To get or set the value of the node.

offsetHeight

To get the height of the element. It includes padding, a border, and a scroll bar.

offsetWidth

To get the width of the element. It includes padding, a border, and a scroll bar.

offsetLeft

To get the horizontal offset position of the HTML element.

offsetParent

To get the offset container of the HTML element.

offsetTop

To get the vertical offset position of the HTML element.

outerHTML

To set or get the outer HTML. It includes the start and end tags.

outerText

To set or get the outer text of the HTML element.

ownerDocument

To get the root element of the document.

parentNode

To get the parent Node of the HTML element.

parentElement

To get the parent element of the HTML element.

previousSibling

To get the previous node at the same level in the DOM tree.

previousElementSibling

To get the previous element at the same level in the DOM tree.

scrollHeight

To get the scrollable height of the element, including the padding.

scrollLeft

To get or set a number of pixels by that element content is scrolled horizontally.

scrollTop

To get or set a number of pixels by that element content is scrolled vertically.

scrollWidth

To get the scrollable width of the element, including the padding.

style

To set or get the style of the element.

tabIndex

To set or get the value of the tabIndex attribute’s value.

tagName

To get the tag name.

textContent

To get the text of the HTML element.

title

To set or get the title of the element.

List of DOM Element Methods

下表包含可在 JavaScript 中用于以 HTML 元素来操作这些元素的方法。

The table below contains the method you can use with HTML elements to manipulate them in JavaScript.

Method

Description

addEventListener()

To add an event handler to the HTML element.

appendChild()

To add a new child element at the last node of the HTML element.

blur()

To remove focus from the HTML element.

click()

To click on the element.

cloneNode()

To clone an element.

closest()

To find the closest element in the DOM tree based on the CSS selector.

compareDocumentPosition()

To compare the document position of two HTML elements.

contains()

To check whether the HTML node contains the particular node.

focus()

To focus on the HTML element.

getAttribute()

To get the particular attribute’s value of the HTML element.

getAttributeNode()

To get the attribute node.

getBoundingClientRect()

To get the element’s size and position relative to the viewport.

getElementById()

To access HTML element by id.

getElementByName()

To access HTML elements using its name.

getElementsByClassName()

To get a collection of child HTML elements that match the class name.

getElementsByTagName()

To get a collection of child HTML elements that match the tag name.

hasAttribute()

To check whether the HTML element contains the particular attribute.

hasAttributes()

To check whether the HTML element contains at least 1 attribute.

hasChildNodes()

To check whether the HTML element has child nodes.

insertAdjacentElement()

To add an HTML element at a position relative to an element.

insertAdjacentHTML()

To insert HTML at a position relative to the element.

insertAdjacentText()

Insert text at a position relative to the text.

insertBefore()

To insert another child node before the existing child node.

isEqualNode()

To check whether two nodes are equal.

isSameNode()

To check whether the two elements are the same node.

matches()

It returns a boolean value based on whether the element matches the CSS selector.

querySelector()

To access the first element that matches the CSS selector.

querySelectorAll()

To access all elements that match the CSS selector.

remove()

It is used to remove the element from the DOM.

removeAttribute()

It returns the particular attribute from the element.

removeAttributeNode()

It removes the attribute node.

removeChild()

It removes the child node from the element.

removeEventListener()

It is used to remove the event listener from the element.

replaceChild()

It is used to replace the particular child node.

scrollIntoView()

It scrolls the element in the viewport or visible area of the browser.

setAttribute()

To update the particular attribute’s value.

setAttributeNode()

To set or update the attribute node.