---
id: 587d7fa6367417b2b2512bc2
title: Add Document Elements with D3
required:
- src: 'https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js'
challengeType: 6
videoUrl: ''
localeTitle: 使用D3添加文档元素
---
## Description
D3有几种方法可以让您在文档中添加和更改元素。 select()
方法从文档中选择一个元素。它接受所需元素名称的参数,并返回文档中与名称匹配的第一个元素的HTML节点。这是一个例子: const anchor = d3.select("a");
上面的示例在页面上查找第一个锚标记,并在变量anchor
为其保存HTML节点。您可以使用其他方法进行选择。示例的“d3”部分是对D3对象的引用,这是您访问D3方法的方式。另外两个有用的方法是append()
和text()
。 append()
方法为要添加到文档的元素接受参数。它将HTML节点附加到选定项目,并返回该节点的句柄。 text()
方法可以设置所选节点的文本,也可以获取当前文本。要设置该值,请在方法的括号内传递一个字符串作为参数。这是一个选择无序列表,附加列表项和添加文本的示例: d3.select( “UL”)
.append( “里”)
.text(“非常重要的项目”);
D3允许您将多个方法与句点链接在一起以连续执行多个操作。
## Instructions
使用select
方法选择文档中的body
标签。然后为其append
一个h1
标签,并将文本“Learning D3”添加到h1
元素中。
## Tests
```yml
tests:
- text: body
应该有一个h1
元素。
testString: 'assert($("body").children("h1").length == 1, "The body
should have one h1
element.");'
- text: h1
元素应该包含文本“Learning D3”。
testString: 'assert($("h1").text() == "Learning D3", "The h1
element should have the text "Learning D3" in it.");'
- text: 您的代码应该访问d3
对象。
testString: 'assert(code.match(/d3/g), "Your code should access the d3
object.");'
- text: 您的代码应该使用select
方法。
testString: 'assert(code.match(/\.select/g), "Your code should use the select
method.");'
- text: 您的代码应该使用append
方法。
testString: 'assert(code.match(/\.append/g), "Your code should use the append
method.");'
- text: 您的代码应该使用text
方法。
testString: 'assert(code.match(/\.text/g), "Your code should use the text
method.");'
```
## Challenge Seed
## Solution
```js
// solution required
```