
Quick Tip: From Elements To Console And Back Using The Command Line API
Since the release of Firebug, the way we develop and debug web sites have changed dramatically. We have moved on from the old alert() and have embraced the awesomeness that is console.log but, did you know that there is actually an entire API, originally developed by the people behind Firebug but now implemented by Webkit in their Web Inspector/Chrome Developer Tools as well as Opera’s Dragonfly and to a very limited degree in IE’s developer tools.
Transcript
Today I want to look at one of the very useful features of the Command Line API and those are $0 and inpsect(). To demonstrate this, open the demo page and your developer tools. Next, expand the article tag as well as the section with the id ‘intro’. Click on the section to bring it into focus.
Open up your console. Now normally if you want to inspect or manipulate the ‘intro’ section, you will enter something like document.getElementById(“intro”); into the console. The Command Line API gives us a nice shortcut to access the current highlighted element. Say we want to see the inner HTML for the element, simply enter the following:
$0.innerHTML;
Want to set something on the element, simple:
$0.style.backgroundColor = "red";
So this covers getting from the selected element into the console and quickly and easily working with the current DOM node. What if you have an element that is deeply nested that you wanted to inspect? Instead of jumping into the HTML tree and clicking around to find it, you can of course right click on the element and select ‘Inspect Element’, there is another really useful shortcut from the console.
Let’s say we know that the element we want to inspect has an id of ‘selected’. Inside console, enter the following:
inspect($("selected"));
Hit enter and viola, focus will jump directly to your element. NOTE: The $(“selected) above will work whether you have jQuery on your page or not as this is another of the functions provided by the Command Line API. Running all of these command quickly fills up your console. Now, you can right click and select ‘Clear Console’ but that’s so boring instead, type clear() and hit enter.
I hope the above saves you some time during your daily development. I look forward to everyone’s comments.
Image Courtesy: kiki follettosa
