Today, I wanted to share a few console tricks that I’ve found useful over the years. Let’s dig in!
A quick aside about opening the console
If you’re already familiar with the developer console, jump to the next section.
console.log() method to print things into the console and see what your code is doing.
// logs "Hi there!" to the console console.log('Hi there!');
The Console is also where any errors or warning about your code will be logged by the browser.
You can open Developer Tools by pressing Command + Option + I on macOS, or Control + Option + I on Windows or Linux. The click on the Console tab in the Developer Tools Window.
You can also open Developer Tools using the GUI Menu.
- In Chromium browsers (Chrome and MS Edge), go to Tools > Developer > Developer Tools.
- In Firefox, go to Tools > Browser Tools > Web Developer Tools.
- In Safari, go to Develop > Show Web Inspector. The Develop menu is hidden by default. To enable it, open Safari Preferences, click on the Advanced tab, and check the Show develop menu in menu bar checkbox.
Trick 1: Getting elements from the
$$() shorthand methods
All of the major browsers include
$$() convenience methods.
With both methods, you pass in any valid CSS selector. The
$() method returns the first matching item, while the
$$() method returns an array (not a NodeList like the
Element.querySelectorAll() method) of matching items.
// Gets the element with an ID of #main let main = $('#main'); // Gets an array of all items with the .sandwich class let sandwiches = $$('.sandwich');
Trick 2: Getting the currently selected item in the Elements tab as a variable
$0 variable in the console tab returns the currently selected item in the Elements tab.
// Cache to a variable for reuse let current = $0;
If you select another element, the previous one gets assigned to the
$1 variable, while the new one replaces it for the
Each time you select another element to view in the Elements tab, the numbers increase by one, allowing you to access a backlog of previously selected elements.
// The previously selected element let previous = $1; // The one before that let furtherBack = $2;