Styling console.log output

I recently learned about a very cool console.log feature. You can use CSS formatting to style the output of console.log. And it’s very easy. All you have to do is use the ‘ %c ‘ formatting tag in your message.

Here’s a simple example:

console.log('%cThis is a %cfun%c console message',
            'font: 24px serif; font-weight:100; color: #228;',
            'font: 30px sans-serif; font-weight:800; color: #F44;',
            'font: 24px serif; font-weight:100; color: #228;'

When you look in the console of the browser, you should see something like this:


Unfortunately this features is not supported in all browsers, which may result in a whole bunch of CSS being written to the console. You should check the browser in your code before using this feature. As far as I know only Chrome and Firefox support this feature.

Poor Mans jQuery

A lot of people use jQuery in their HTML/JavaScript applications. There’s nothing wrong with that. But I’ve seen a lot of people use jQuery only to make it easy to find elements and they are not using any of the other jQuery functions. It’s pretty clear that writing a single ‘ $ ‘ instead of the way longer usages of various function on the ‘document‘ object, like getElementById. One of the functions on the ‘document’ object is the querySelectorAll function. This function brings a similar experience to vanilla JavaScript by taking selectors as a parameter.  So if we take a look at the example below. This show a fairly complicated selector you might find in an application.

I personally don’t like writing ‘document.querySelectorAll every time I need to find some things in the DOM, and many people with me. That’s why a lot of developers include jQuery in their project. To be able to use a similar syntax as jQuery is using I often add the following line somewhere at the start of my JavaScript code:

window.$ = function (selector) { return document.querySelectorAll(selector); };

Here’s the earlier example, but with the poor-mans-jQuery added.

It’s not perfect and sometimes I add a context or something to that function if it is needed for that project, but it works fine in most cases.

As a last note, always look at the performance. If you are using selectors a lot, like in a big for-iteration, you might want to use the document.getElementsByClass function or something similar. These have less overhead and are somewhat faster.