使用控制台与 DOM 交互Use the Console to interact with the DOM

控制台 工具 并不仅仅是用于 日志记录信息运行任意 JavaScriptThe Console tool isn't only for logging information or to run arbitrary JavaScript. 这也是在浏览器中与网页交互的一种很好的方法。It also is a great way to interact with the webpage in the browser. 请考虑它是 Inspect 工具的 脚本环境版本Consider it a script-environment version of the Inspect tool.

从 DOM 读取Read from the DOM

若要引用网页的标题,请完成以下操作。To reference the header of the webpage, complete the following actions.

  1. 打开“控制台”。Open the Console.

    • 选择 Control + Shift + J (Windows、Linux) 或 Command + Option + J (macOS)。Select Control+Shift+J (Windows, Linux) or Command+Option+J (macOS).
  2. 在控制台中键入或复制并粘贴以下 代码段Type or copy and paste the following code snippet in the Console.

    document.querySelector('header')
    

若要在控制台中获取对标头的引用,请使用 document.querySelector

如果选择鼠标 Shift + Tab 光标或将鼠标光标移到 HTML 结果上,DevTools 会突出显示标头。If you select Shift+Tab or move your mouse cursor over the HTML result, DevTools highlights the header for you.

DevTools 突出显示你在控制台中选择的部分

操作 DOMManipulate the DOM

您也可以操作网页。You may manipulate the webpage, too. 例如,如果复制并粘贴或在控制台中键入以下内容,标题周围**** 将显示绿色边框。For example, if you copy and paste or type the following into the Console, a green border displays around the header.

document.querySelector('header').style.border = '2em solid green'

若要向元素添加边框,请使用控制台

根据网页的复杂性,可能很难找到正确的要操作的元素。Depending on the complexity of the webpage, It may be daunting to find the right element to manipulate. 但可以使用 Inspect 工具帮助你。But you may use the Inspect tool to help you. 假设你想要操作页 Documentation 眉中的部分。Say you want to manipulate the Documentation part in the header.

显示你在屏幕上检查的元素

若要获取对要操作的元素的直接引用,请完成以下操作。To get a direct reference to the element to manipulate, complete the following actions.

  1. 使用 Inspect 工具选择元素。Use the Inspect tool to choose the element.

    若要选择元素,请使用检查器工具

  2. 选择它,DevTools 跳转到 "元素" 工具。Choose it and DevTools jumps to the Elements tool.

  3. 选择 ... DOM 视图中元素旁边的菜单。Choose the ... menu next to the element in the DOM view.

    所选元素显示在元素工具的 DOM 树中,选择溢出菜单以获取更多功能

  4. 打开上下文菜单并选择 Copy > Copy JS PathOpen the contextual menu and choose Copy > Copy JS Path.

    从元素工具的 DOM 视图中的元素复制 JavaScript 路径

  5. 返回到 控制台并粘贴 命令。Go back to the Console and paste the command.

若要将链接文本更改为 My Playground ,请 .textContent = "My Playground" 添加到之前粘贴的命令中。To change the text of the link to My Playground, add .textContent = "My Playground" to the command you previously pasted.

使用控制台更改元素的内容

使用你想要在控制台中执行的任何 JavaScript DOM 操作Use any JavaScript DOM manipulations you want to do in the Console. 为了更方便, 控制台 提供了一些帮助程序方法。To make it more convenient, the Console comes with a few helper methods.

有用的控制台实用程序方法Helpful Console utility methods

许多便利的方法和快捷方式都作为控制台 实用程序提供给你。Many convenience methods and shortcuts are available to you as Console Utilities. 其中一些方法非常强大,也是您可能作为过去一系列语句撰写 console.log() 的一些内容。Some of the methods are incredibly powerful and are things you probably wrote as a series of console.log() statements in the past.

$ 的电源The power to the $

$控制台中具有特殊功能,你可能从 jQuery 中记住这一点。The $ has special powers in Console and you may remember that from jQuery.

  • $_ 存储最后一个命令的结果。stores the result of the last command. 因此,如果你键入 2 + 2 并选择 Enter ,然后键入 ,控制台 $_ 将显示**** 4 你 。So, if you type 2 + 2 and select Enter, and then type $_, the Console displays you 4.
  • $0 $4是最后检查的元素的堆栈, $0 始终为最新元素。to $4 is a stack of the last inspected elements $0 is always the newest one. 因此,在上一示例中,你只需在 Inspector 工具中选择 元素并键入 $0.textContent = "My Playground" ,以获得相同的效果。So in the earlier example, you just chose the element in the Inspector tool and type $0.textContent = "My Playground" to get the same effect.
  • $x() 允许您使用 XPATH 选择 DOM 元素。allows you to choose DOM elements using XPATH.
  • $() $$()和 是 和 的 document.querySelector() 较短版本 document.querySelectorAll()and $$() are shorter versions of for document.querySelector() and document.querySelectorAll().

例如,以下代码段检索网页 \ (中所有的链接,就像 ) 的简短内容一样,将链接显示为可排序表,以复制并粘贴到 Excel 中。 $$('a') document.querySelectorAll('a')For example, the following code snippet retrieves all the links in the webpage (as $$('a') is short for document.querySelectorAll('a')) and displays the links as a sortable table to copy and paste, for example, into Excel.

console.table($$('a'),['href','text']);

获取网页中所有的链接,将结果显示为表格

但是,如果你不希望显示信息,但希望获取它作为数据。However, if you don't want to display the information, but you want to grab it as data. 快捷方式 $$('a') 提供定位链接以及每个链接的所有属性。The $$('a') shortcut provides the anchor links and all of the properties for each one. 问题是您只需要链接和相关文本。The problem is that you only want the links and the related text.

$$ 快捷方式返回的信息过多

快捷方式 $$ 具有一项有趣的额外功能。The $$ shortcut has an interesting extra feature. 快捷方式为你提供所有方法,而不是返回纯 NodeList document.querySelectorAll() like $$ ArrayInstead of returning a pure NodeList like document.querySelectorAll(), the $$ shortcut gives you all of the Array methods. 使用 map() 方法将信息减少为你需要的信息。Use map() method to reduce the information to what you need.

$$('a').map(a => {
    return {url: a.href, text: a.innerText}
})

代码段将返回所有链接的 Array,作为具有 urltext 属性的对象。The code snippet returns an Array of all the links as objects with url and text properties.

使用 $$ 上的映射将信息筛选到最低

您尚未完成,多个链接是网页的内部链接或具有空文本。You aren't done yet, several links are internal links to the webpage or have empty text. 使用 filter 方法可删除内部链接。Use the filter method to get rid of the internal links.

$$('a').map(a => {
    return {text: a.innerText, url: a.href}
}).filter(a => {
    return a.text !== '' && !a.url.match('docs.microsoft.com')
})

获取不为空且为外部的链接

如网页开始部分显示,您还可以更改这些元素。As displayed at the start of the webpage, you may also change these elements. 例如,以下代码段在所有外部链接周围创建绿色边框:For example, the following code snippet creates a green border around all external links:

$$('a[href^="https://"]').forEach(
  a => a.style.border = '1px solid green'
)

若要突出显示所有外部链接,请在每个链接周围添加绿色边框

使用 CSS 选择器功能,而不是编写复杂的 JavaScript 来筛选结果。Instead of writing complex JavaScript to filter results, use the power of CSS selectors.

若要为网页上不是内嵌图像的所有图像创建 和 信息的表, src alt 请完成以下操作。To create a table of the src and alt information for all images on the webpage that aren't inline images, complete the following actions.

  1. 打开“控制台”。Open the Console.
  2. 键入或复制并粘贴以下代码段。Type or copy and paste the following code snippet.
console.table($$('img:not([src^=data])'), ['src','alt'])

若要选择元素,请使用复杂的 CSS 选择器

准备好进行更复杂的示例了吗?Ready for an even more complex example? 通过 markdown 生成的 HTML 网页(如本文)具有每个标题的自动 ID 值,以允许您深层链接到该部分。HTML webpages generated from markdown like this article, have automatic ID values for each heading to allow you to deep link to that section. 例如,对 # New features 进行更改 <h1 id="new-features">New features</h1>For example, a # New features changes to <h1 id="new-features">New features</h1>.

若要列出要复制和粘贴的所有自动标题,请完成以下操作。To list of all of the automatic headings to copy and paste, complete the following actions.

  1. 打开“控制台”。Open the Console.
  2. 键入或复制并粘贴以下代码段。Type or copy and paste the following code snippet.
let out = '';
$$('#main [id]').filter(
    elm => {return elm.nodeName.startsWith('H')}
).forEach(elm => {
   out += elm.innerText + "\n" + 
          document.location.href + '#' +
          elm.id + "\n";
});
console.log(out);

结果是包含每个标题的内容的文本,后跟指向该标题的完整 URL。The result is text that contains content for each heading followed by the full URL that points to it.

从网页获取所有标题和生成的 URL

清除并复制Clean up with clear and copy

在控制台中 开发时,情况可能会变得混乱。When developing in the Console, things may get messy. 你可能会觉得在复制和粘贴时尝试选择结果感到沮丧。You may find it frustrating to try to choose results while you copy and paste. 以下两种实用程序方法可帮助您。The following two utility methods help you.

  • copy() 将你提供的任何内容复制到剪贴板。copies whatever you give it to the clipboard. copy()在将该方法与复制最后的结果混合使用时, $_ 该方法尤其有用。The copy() method is especially useful when you mix it with $_ that copies the last result.
  • clear() 清除 控制台clears the Console.

读取和监视事件Read and monitor events

Console 的另外两种有趣的 实用程序方法处理 事件处理。Two other interesting utility methods of Console deal with event handling.

  • getEventListeners(node) 列出节点的所有事件侦听器。lists all the event listeners of a node.
  • monitorEvents(node, events) 监视和记录节点上发生的事件。monitors and logs the events that happen on a node.

若要列出分配给网页中第一个表单的所有事件侦听器,请完成以下操作。To list all of the event listener assigned to the first form in the webpage, complete the following actions.

  1. 打开“控制台”。Open the Console.

  2. 键入或复制并粘贴以下代码段。Type or copy and paste the following code snippet.

    getEventListeners($('form')); 
    

获取网页中第一个表单的所有事件侦听器

监视时,每次对指定元素进行更改时,都会**** 在控制台中收到通知。When you monitor, you to get a notification in the Console every time something changes to the specified elements. 将要侦听的事件定义为第二个参数。You define the events you want to listen to as a second parameter. 定义要监视的事件非常重要,否则将报告元素发生的任何事件。It is important for you to define the events that you want to monitor, otherwise any event happening to the element is reported.

若要每次滚动时在 控制台 中收到通知,请调整窗口大小,或当用户在搜索表单中输入内容时,请完成以下操作。To get a notification in the Console every time you scroll, resize the window, or when the user types in the search form, complete the following actions.

  1. 打开“控制台”。Open the Console.

  2. 键入或复制并粘贴以下代码段。Type or copy and paste the following code snippet.

    monitorEvents(window, ['resize', 'scroll']);
    monitorEvents($0, 'keyup');
    

控制台显示窗口上发生的每个滚动事件

若要记录当前选择的元素上的任何键操作,请专注于标题中的搜索表单并选择一些键。To log any key action on the currently chosen element, focus on the search form in the header and select some keys.

控制台显示窗体上发生的键更新事件

若要停止它,请删除通过以下代码段设置的监视。To stop it, remove the monitoring you set using the following code snippet.

unmonitorEvents(window, ['resize', 'scroll']);
unmonitorEvents($0, 'key');

重用 DOM 操作脚本Reuse DOM manipulation scripts

你可能会发现从控制台操作 DOM 非常有用You may find it useful to manipulate the DOM from the Console. 你很快就会遇到控制台作为开发 平台 的限制。You may soon run into the limitations of the Console as a development platform. 好消息是,DevTools 中的" 源"工具提供了功能齐全的开发环境。The good news is that the Sources tool in DevTools offers a fully featured development environment. "源 "工具中,可以完成以下操作。In the Sources tool, you may complete the following actions.

  • 将控制台脚本存储为代码段Store your scripts for the Console as Snippets.
  • 使用键盘快捷方式或编辑器在网页中运行脚本。Run the scripts in a webpage using a keyboard shortcut or the editor.

与 Microsoft Edge 开发人员工具团队联系Getting in touch with the Microsoft Edge DevTools team

使用以下选项讨论帖子中的新功能和更改,或与 DevTools 相关的任何其他内容。Use the following options to discuss the new features and changes in the post, or anything else related to DevTools.

  • 使用“发送反馈”图标发送反馈,或在 DevTools 中选择Alt+Shift+I \ (Windows、Linux) 或 Option+Shift+I \ (macOS)。Send your feedback using the Send Feedback icon or select Alt+Shift+I (Windows, Linux) or Option+Shift+I (macOS) in DevTools.
  • 发推 @EdgeDevToolsTweet at @EdgeDevTools.
  • 我们想要的 Web 提交建议。Submit a suggestion to The Web We Want.
  • 若要提交有关本文的错误,请使用以下“反馈” 部分。To file bugs about this article, use the following Feedback section.

Microsoft Edge DevTools 中的“发送反馈”图标