JavaScript DOM简介

The Javascript DOM (Document Object Model) is an interface that allows developers to manipulate the content, structure and style of a website. In this article, we will learn what the DOM is and how you can manipulate it using Javascript. This article can also be used as a reference for the basic DOM operations.

Javascript DOM(文档对象模型)是一个接口,允许开发人员操纵网站的内容,结构和样式。 在本文中,我们将学习DOM是什么以及如何使用Javascript操作它。 本文还可以用作基本DOM操作的参考。

什么是DOM? (What is the DOM?)

At the most basic level, a website consists of an HTML and CSS document. The browser creates a representation of the document known as Document Object Model (DOM). This document enables Javascript to access and manipulate the elements and styles of a website. The model is built in a tree structure of objects and defines:

在最基本的级别上,网站由HTML和CSS文档组成。 浏览器创建文档的表示形式,称为文档对象模型(DOM)。 该文档使Javascript可以访问和操纵网站的元素和样式。 该模型建立在对象的树结构中,并定义:

  • HTML elements as objects

    HTML元素作为对象
  • Properties and events of the HTML elements

    HTML元素的属性和事件
  • Methods to access the HTML elements

    访问HTML元素的方法

The places of the elements are referred to as nodes. Not only elements get nodes but also the attributes of elements and text get their own node (attribute-nodes and text-nodes).

元素的位置称为节点。 不仅元素获得节点,元素和文本的属性也获得其自己的节点(属性节点和文本节点)。

DOM文件 (DOM Document)

The DOM Document is the owner of all other objects in your webpage. That means if you want to access any object on your webpage you always have to start with the document. It also contains many important properties and methods that enable us to access and modify our website.

DOM文档是网页中所有其他对象的所有者。 这意味着,如果您要访问网页上的任何对象,则始终必须从文档开始。 它还包含许多重要的属性和方法,这些属性和方法使我们能够访问和修改我们的网站。

查找HTML元素 (Finding HTML Elements)

Now that we understand what the DOM document is we can start getting our first HTML elements. There are many different ways to do so using the Javascript DOM here are the most common:

现在我们了解了DOM文档是什么,我们可以开始获取第一个HTML元素。 使用Javascript DOM的方式有很多,这是最常见的:

通过ID获取元素 (Get element by ID)

The getElementById() method is used to get a single element by its id. Let’s look at an example:

getElementById()方法用于通过其ID获取单个元素。 让我们看一个例子:

var title = document.getElementById(‘header-title’);

Here we get the element with the id of header-title and save it into a variable.

在这里,我们获得带有标题标题ID的元素,并将其保存到变量中。

通过类名获取元素 (Get elements by class name)

We can also get more than one object using the getElementsByClassName() method which returns an array of elements.

我们还可以使用getElementsByClassName()方法获得一个以上的对象,该方法返回一个元素数组。

var items = document.getElementsByClassName(‘list-items’);

Here we get all items with the class list-items and save them into a variable.

在这里,我们获得所有带有类列表项的项目 ,并将它们保存到变量中。

通过标签名称获取元素 (Get element by tag name)

We can also get our elements by tag name using the getElementsByTagName() method.

我们还可以使用getElementsByTagName()方法通过标签名称获取元素。

var listItems = document.getElementsByTagName(‘li’);

Here we get all li elements of our HTML document and save them into a variable.

在这里,我们获得了HTML文档的所有li元素,并将它们保存到变量中。

查询选择器 (Queryselector)

The querySelector() method returns the first element that matches a specified CSS selector. That means that you can get elements by id, class, tag and all other valid CSS selectors. Here I just list a few of the most popular options.

querySelector()方法返回与指定的CSS选择器匹配的第一个元素 这意味着您可以通过id,class,tag和所有其他有效CSS选择器来获取元素。 在这里,我只列出了一些最受欢迎的选项。

Get by id:

按编号获取:

var header = document.querySelector(‘#header’)

Get by class:

上课:

var items = document.querySelector(‘.list-items’)

Get by tag:

通过标签获取:

var headings = document.querySelector(‘h1’);

Get more specific elements:

获取更多具体元素:

We can also get more specific elements using CSS Selectors.

我们还可以使用CSS选择器获得更多特定元素。

document.querySelector(“h1.heading”);

In this example we search for a tag and a class at the same time and return the first element that passes the CSS Selector.

在此示例中,我们同时搜索标签和类,并返回传递CSS选择器的第一个元素。

查询选择器 (Queryselectorall)

The querySelectorAll() method is completely the same as the querySelector() except that it returns all elements that fit the CSS Selector.

querySelectorAll()方法与querySelector()完全相同,只不过它返回所有适合CSS选择器的元素。

var heading = document.querySelectorAll(‘h1.heading’);

In this example, we get all h1 tags that have a class of heading and store them in an array.

在此示例中,我们获得所有具有标题类的h1标签并将它们存储在数组中。

更改HTML元素 (Changing HTML Elements)

The HTML DOM allows us to change the content and style of an HTML element by changing its properties.

HTML DOM允许我们通过更改HTML元素的属性来更改其内容和样式。

更改HTML (Changing the HTML)

The innerHTML property can be used to change the content of an HTML element.

innerHTML属性可用于更改HTML元素的内容。

document.getElementById(“#header”).innerHTML = “Hello World!”;

In this example we get the element with an id of header and set the inner content to “Hello World!”.

在此示例中,我们获取具有标头ID的元素,并将内部内容设置为“ Hello World!”。

InnerHTML can also be used to put tags in another tag.

InnerHTML也可以用于将标签放置在另一个标签中。

document.getElementsByTagName("div").innerHTML = "<h1>Hello World!</h1>"

Here we put a h1 tag into all already existing div.

在这里,我们将h1标签放入所有现有的div中。

更改属性值 (Changing a value of an attribute)

You can also change the value of an attribute using the DOM.

您还可以使用DOM更改属性的值。

document.getElementsByTag(“img”).src = “test.jpg”;

In this example we change the src of all <img/> tags to test.jpg.

在此示例中,我们将所有<im g /> 标签的src更改为te st.jpg。

改变风格 (Changing the style)

To change the style of an HTML element we need to change the style property of our elements. Here is an example syntax for changing styles:

要更改HTML元素的样式,我们需要更改元素的style属性。 这是更改样式的示例语法:

document.getElementById(id).style.property = new style

Now lets look at an example where we get an element and change the bottom border to a solid black line:

现在让我们看一个示例,在该示例中我们获得了一个元素并将底部边框更改为实心黑线:

document.getElementsByTag(“h1”).style.borderBottom = “solid 3px #000”;

The CSS properties need to be written in camelcase instead of the normal css property name. In this example we used borderBottom instead of border-bottom.

CSS属性需要用驼峰式书写,而不是普通CSS属性名称。 在此示例中,我们使用borderBottom而不是border-bottom。

添加和删​​除元素 (Adding and deleting elements)

Now we will take a look at how we can add new elements and delete existing ones.

现在我们来看看如何添加新元素和删除现有元素。

添加元素 (Adding elements)
var div = document.createElement(‘div’);

Here we just create a div element using the createElement() method which takes a tagname as a parameter and saves it into a variable. After that we just need to give it some content and then insert it into our DOM document.

在这里,我们只是使用createElement()方法创建一个div元素,该方法将标记名作为参数并将其保存到变量中。 之后,我们只需要提供一些内容,然后将其插入到我们的DOM文档中即可。

var newContent = document.createTextNode("Hello World!"); 
div.appendChild(newContent);
document.body.insertBefore(div, currentDiv);

Here we create content using the createTextNode() method which takes a String as a parameter and then we insert our new div element before a div that already exists in our document.

在这里,我们使用createTextNode()方法创建内容,该方法将String作为参数,然后在文档中已经存在的div之前插入新的div元素。

删除元素 (Deleting elements)
var elem = document.querySelector('#header');
elem.parentNode.removeChild(elem);

Here we get an element and delete it using the removeChild() method.

在这里,我们得到一个元素,并使用removeChild()方法将其删除。

替换元素 (Replace elements)

Now let’s take a look at how we can replace items.

现在让我们看一下如何替换物品。

var div = document.querySelector('#div');
var newDiv = document.createElement(‘div’);
newDiv.innerHTML = "Hello World2"
div.parentNode.replaceChild(newDiv, div);

Here we replace an element using the replaceChild() method. The first argument is the new element and the second argument is the element which we want to replace.

在这里,我们使用replaceChild()方法替换元素。 第一个参数是新元素,第二个参数是我们要替换的元素。

直接写入HTML输出流 (Writing directly into the HTML output stream)

We can also write HTML expressions and JavaScript directly into the HTML output stream using the write() method.

我们还可以使用write()方法将HTML表达式和JavaScript直接写入HTML输出流。

document.write(“<h1>Hello World!</h1><p>This is a paragraph!</p>”);

We can also pass JavaScript expressions like a date object.

我们还可以像日期对象一样传递JavaScript表达式。

document.write(Date());

The write() method can also take multiple arguments that will be appended to the document in order of their occurrence.

write()方法还可以采用多个参数,这些参数将按照出现的顺序附加到文档中。

事件处理程序 (Event Handlers)

The HTML DOM also allows Javascript to react to HTML events. Here I’ve just listed some of the most important ones:

HTML DOM还允许Javascript对HTML事件做出React。 在这里,我列出了一些最重要的信息:

  • mouse click

    鼠标点击
  • page load

    页面加载
  • mouse move

    鼠标移动
  • input field change

    输入栏变更
分配事件 (Assign Events)

You can define events directly in your HTML code using attributes on your tags. Here is an example of an onclick event:

您可以使用标签上的属性直接在HTML代码中定义事件。 这是一个onclick事件的示例:

<h1 onclick=”this.innerHTML = ‘Hello!’”>Click me!</h1>

In this example, the text of the <h1/> will change to “Hello!” when you click the button.

在此示例中,<h1 />的文本将更改为“ Hello!”。 当您单击按钮时。

You can also call functions when an event is triggered as you can see in the next example.

您也可以在触发事件时调用函数,如下面的示例所示。

<h1 onclick=”changeText(this)”>Click me!</h1>

Here we call the changeText() method when the button is clicked and pass the element as an attribute.

在此,当单击按钮并将元素作为属性传递时,我们将调用changeText()方法。

We can also assign the same events in our Javascript code.

我们还可以在Javascript代码中分配相同的事件。

document.getElementById(“btn”).onclick = changeText();
分配事件监听器 (Assign Events Listeners)

Now let’s look at how you can assign event listeners to your HTML elements.

现在,让我们看一下如何将事件侦听器分配给HTML元素。

document.getElementById(“btn”)addEventListener('click', runEvent);

Here we just assigned a clickevent that calls the runEvent method when our btn element is clicked.

在这里,我们只分配了一个clickevent,当单击btn元素时,该事件将调用runEvent方法。

You can also assign multiple events to a single element:

您还可以将多个事件分配给单个元素:

document.getElementById(“btn”)addEventListener('mouseover', runEvent);

节点关系 (Node Relationships)

The nodes in the DOM Document have a hierarchical relationship to each other. This means that the nodes are structured like a tree. We use the terms parent, sibling and child to describe the relationship between nodes.

DOM文档中的节点之间具有层次关系。 这意味着节点的结构像一棵树。 我们使用“父”,“兄弟”和“子”一词来描述节点之间的关系。

The top node is called the root and is the only node that has no parent. The root in a normal HTML document is the <html/> tag because it has no parent and is the top tag of the document.

顶层节点称为根节点,并且是唯一没有父节点的节点。 普通HTML文档中的根是<html />标记,因为它没有父级,并且是文档的顶部标记。

We can navigate between nodes using these properties:

我们可以使用以下属性在节点之间导航:

  • parentNode

    parentNode
  • childNodes

    子节点
  • firstChild

    第一个孩子
  • lastChild

    最后一个孩子
  • nextSibling

    nextSibling

Here is an example how you can get the parent element of an h1.

这是一个如何获取h1父元素的示例。

var parent = document.getElementById(“heading”).parentNode

结论 (Conclusion)

You made it all the way until the end! Hope that this article helped you understand the Javascript DOM and how to use it to manipulate elements on your website.

一路走到最后! 希望本文能帮助您了解Javascript DOM以及如何使用它来操纵网站上的元素。

If you want to read more articles just like this one you can visit my website or start following my newsletter.

如果您想像这样阅读更多文章,则可以访问我的网站或开始关注我的新闻通讯

If you have any questions or feedback, let me know in the comments down below.

如果您有任何疑问或反馈,请在下面的评论中告诉我。

翻译自: https://www.freecodecamp.org/news/an-introduction-to-the-javascript-dom-512463dd62ec/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值