If you're entering the same code into the Console tool repeatedly, consider saving the code as a snippet instead, and then running the snippet. Snippets are scripts that you author in the Sources tool. Snippets have access to the JavaScript context of the webpage, and you can run snippets on any webpage. Snippets can be used to alter a webpage, such as to change its content or appearance, or to extract data.
The following screenshot shows Microsoft Edge with a webpage on the left and DevTools on the right. The Sources tool is open, displaying the source code of the snippet that's selected in the Snippets tab. The snippet code was run, making changes to the webpage:
The snippet source code is shown below:
// Change the background color to "dimgrey".
document.body.style.backgroundColor = "dimgrey";
// Add a paragraph at the bottom of the document.
const p = document.createElement("p");
p.textContent = "Hello world";
p.style.color = "white";
p.style.fontSize = "2rem";
document.body.appendChild(p);
// Log a message to the console.
console.log("Hello world");
The code changes the background color of the webpage to dimgrey, adds a new line of text at the bottom of the webpage, and logs a message to the Console tool.
When you run a snippet on a webpage, the snippet's source code is added to the current webpage. For more information about changing the existing code of a webpage instead of adding new code, see Override webpage resources with local copies (Overrides tab).
Include all your code in one file
The security settings of most webpages block from loading other scripts in snippets. For this reason, you must include all your code in one file.
Open the Snippets tab
The Snippets tab is grouped with the Page tab in the Navigator pane, on the left of the Sources tool.
To open the Snippets tab:
To open DevTools, right-click the webpage, and then select Inspect. Or, press Ctrl+Shift+I (Windows, Linux) or Command+Option+I (macOS). DevTools opens.
In DevTools, on the Activity Bar, select the Sources tab. If that tab isn't visible, click the More tools () button.
In the Navigator pane (on the left), select the Snippets tab. To access the Snippets option, you might need to click the More tabs () button.
Open the Snippets tab from the Command Menu
You can also open the Snippets tab by using the Command Menu:
Select anything in DevTools, so that DevTools has focus.
Press Ctrl+Shift+P (Windows, Linux) or Command+Shift+P (macOS) to open the Command Menu.
Start typing "snippets", select Show Snippets, and then press Enter to run the command:
Practice the beginning steps of web development by creating a simple web project in Visual Studio Code that contains a web page, a CSS file, and a JavaScript file. Learn how to use developer tools in your browser to check your work.